Skip to content

Getting started with 3D and React

🔗Introduction

In this tutorial, we will build 3D designs with React using the react-three-fiber package. What is react-three-fiber? It’s a three.js for React.js, and it is a powerful renderer that helps render 3D models and animations for React, and its native applications.

🔗Install

First, let’s create a new React project or Next.JS project.

npx create-react-app react-3d

Then, we need to install two packages:three and react-three-fiber.

npm: npm install three @react-three/fiber

yarn: yarn add three @react-three/fiber

🔗Create your first sense

Go to App.js and copy and paste the following code:

import React, { useRef, useState } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';

function Box(props) {
  // This reference will give us direct access to the mesh
  const mesh = useRef();
  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false);
  const [active, setActive] = useState(false);
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (mesh.current.rotation.x += 0.01));
  // Return view, these are regular three.js elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? 1.5 : 1}
      onClick={(event) => setActive(!active)}
      onPointerOver={(event) => setHover(true)}
      onPointerOut={(event) => setHover(false)}
    >
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  );
}

function App() {
  return (
    <Canvas style={{ height: '100vh' }}>
      <ambientLight />
      <pointLight position={[10, 10, 10]} />
      <Box position={[-1.2, 0, 0]} />
      <Box position={[1.2, 0, 0]} />
    </Canvas>
  );
}

export default App;

Save. The result will look like this:

react 3d - screenshot1

So, let’s look at the code:

  • Canvas is your main scene.
  • mesh is the box objects.
  • pointLight is the light for the scene.
  • ambientLight is a global light that illuminates all objects in the scene equally, and this light cannot be used to cast shadows as it does not have a direction.

🔗Cameras

We have three types of cameras that react-fiber-three support:

  • PerspectiveCamera: that can set itself as the default. react 3d -screenshot 2

  • OrthographicCamera: with this camera, all objects appear at the same scale. react 3d -screenshot 3

  • CubeCamera: Creates 6 cameras that render the scene react 3d - screenshot 4

🔗Events

React three fiber package offers us a lot of events that you can use it make your users interact with the 3D design like we saw with the Box element in the first example.

Some of the events:

  • onClick: When the user clicks on the object.
  • onContextMenu: When the user opens the context menu on the object (Right click)
  • onDoubleClick: When the user double clicks on the object.
  • onWheel: When the user uses the mouse wheel to scroll on the object.
  • onPointerUp: When the user moves the cursor up.
  • onPointerDown: When the user moves the cursor down.
  • onPointerOver: When the user hovers with the cursor on the object.
  • onPointerOut: When the user moves out of the object with the cursor.
  • onUpdate: When the object is being updated.

🔗Loading models

With react-three-fiber and three, you can import 3D models and use them in your scene! There are many types of 3D model extensions that you can import with this method, including GLTF, FBX, OBJ, etc...

To import an external model, you will first need to import two things in your file: useLoader hook from react-three-fiber, and the model extension loader from three.js.

For example:

import { useLoader } from '@react-three/fiber';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

And then import the model using the useLoader hook.

const gltf = useLoader(GLTFLoader, '/Model.gltf');

Finally, you can use it in your scene.

<primitive object="{gltf.scene}" />

You can see a live example here.

🔗Animation

Finally, we will talk about how to animate your models. We will need to import useFrame hook! It is a Fiber hook that lets you execute code on every frame of Fiber's render loop. This can have a lot of uses, but we will focus on building an animation with it.

First, import it.

import { useFrame } from '@react-three/fiber';

Create a react ref:

const myMesh = React.useRef();

Then connect this ref with your mesh.

<mesh ref="{myMesh}"></mesh>

Finally, start animating it using useFrame.

useFrame(({ clock }) => {
  myMesh.current.rotation.x = clock.getElapsedTime();
  myMesh.current.rotation.y = clock.getElapsedTime();
});

In this article, we walked through how to install react-three-fiber, and how to make basic objects. In the next article, we will learn how to create a product landing page with it, so stay tuned!


This Dot Labs is a development consultancy focused on providing staff augmentation, architectural guidance, and consulting to companies.

We help implement and teach modern web best practices with technologies such as React, Angular, Vue, Web Components, GraphQL, Node, and more.

You might also like

ReactJS

Taming Forms With react-hook-form

ReactJS

React.js 17: No New Features and New JSX Transform

ReactJS

Adding React to your ASP.NET MVC web app

ReactJS

Supercharging Next.js Development with TailwindCSS