Blog

How to Add React Three Fiber to a React App to Show a Cube

How to Add React Three Fiber to a React App to Show a Cube

React Three Fiber is a powerful library that allows you to use Three.js in React. It's a great tool for adding 3D graphics to your web applications. In this tutorial, we'll walk through the steps to create a simple React app that displays a rotating cube using React Three Fiber.

Prerequisites

Before we begin, make sure you have the following installed on your machine:

  • Node.js
  • npm or yarn

Step 1: Set Up Your React App

First, create a new React app using Create React App. Open your terminal and run:

npx create-react-app react-three-fiber-cube cd react-three-fiber-cube

Step 2: Install React Three Fiber and Three.js

Next, we need to install React Three Fiber and Three.js. Run the following command in your project directory:

npm install @react-three/fiber three

or if you're using yarn:

yarn add @react-three/fiber three

Step 3: Create the Cube Component

Create a new file named Cube.js in the src directory and add the following code:

// src/Cube.js import React from 'react'; import { useFrame } from '@react-three/fiber'; function Cube(props) { const meshRef = React.useRef(); useFrame(() => { meshRef.current.rotation.x += 0.01; meshRef.current.rotation.y += 0.01; }); return ( <mesh {...props} ref={meshRef}> <boxGeometry args={[1, 1, 1]} /> <meshStandardMaterial color={'orange'} /> </mesh> ); } export default Cube;

This component defines a simple cube that rotates on its x and y axes.

Step 4: Create the Scene Component

Now, create another file named Scene.js in the src directory and add the following code:

// src/Scene.js import React from 'react'; import { Canvas } from '@react-three/fiber'; import Cube from './Cube'; function Scene() { return ( <Canvas> <ambientLight /> <pointLight position={[10, 10, 10]} /> <Cube position={[0, 0, 0]} /> </Canvas> ); } export default Scene;

The Scene component sets up the canvas and the lighting. It also adds the Cube component we created earlier.

Step 5: Use the Scene Component in App.js

Replace the contents of App.js with the following code:

// src/App.js import React from 'react'; import Scene from './Scene'; import './App.css'; function App() { return ( <div className="App"> <Scene /> </div> ); } export default App;

Step 6: Run Your App

Now, you can start your React app by running:

npm start

or if you're using yarn:

yarn start

Open your browser and navigate to http://localhost:3000. You should see a rotating orange cube!

Conclusion

You've successfully added React Three Fiber to your React app and created a rotating cube. This is just the beginning of what you can do with React Three Fiber and Three.js. Explore further and create amazing 3D graphics for your web applications!