react-three-fiber

Creating our first cube

Let's create our first cube using react-three-fiber. The first thing we need to do is import Canvas from react-three-fiber and we need to wrap the parent of the 3D scene with it.

You can also just wrap the whole app like so:

import ReactDOM from "react-dom";
import React from "react";
import { Canvas } from "react-three-fiber";
ReactDOM.render(
<Canvas>
<Scene />
</Canvas>,
document.getElementById("root")
);

We are all set up to create our scene component and in there add our first cube.

To make show any type of object in our scene we need to create a mesh, and that consists of:

  • A geometry, in this case our cube but it can be any geometry from threejs or even a custom model you made in blender or any other software.
  • A material, this tells the mesh how this object will be filled. In our case we will just add a simple color that reacts to light.

We can now create a these components and wrap them in a mesh like so:

function Scene() {
return (
<mesh>
<boxGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial attach="material" color="#6be092" />
</mesh>
);
}

We have a geometry but it has two issues, it's black and it looks like it's 2D as we can only see one side of it.

Let's rotate it a bit just so we can see it better:

function Scene() {
return (
<mesh rotation={[0, 10, 0]}>
<boxGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial attach="material" color={"#6be092"} />
</mesh>
);
}

In the next chapter we will learn about lights.

Edit this page on GitHub