How to make a 3D cube in React using react-three-fiber

React JSJavascript LibraryFront End Technology

In this article, we will see how to use Three.js in React by using a third-party package react-three-fiber. Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL

Example

First of all, install the react-three-fiber package −

npm i --save @react-three/fiber three

threejs and react-three/fiber will be used to add webGL renderer to the website.

Add the following lines of code in App.js

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

function Box(props) {
   const mesh = useRef();
   useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01));
   return (
      <mesh {...props} ref={mesh}>
         <boxGeometry args={[3, 3, 3]} />
         <meshStandardMaterial color={"orange"} />
      </mesh>
   );
}
export default function App() {
   return (
      <Canvas>
         <ambientLight />
         <Box position={[0, 0, 0]} />
      </Canvas>
   );
}

Explanation

  • <mesh> is used to make a threeJS object, and inside it, we created a box using boxGeometry which is used to define the size, shape and structural things.

  • We used meshStandardMaterial to design our geometrical structure.

  • <mesh> is used to combine the structure and the design together. We created a functional component inside which we made a reference.

  • Then we created a Frame which is required to change the position of our mesh object or Cube. Next, we added the frame to reference and gave reference to mesh.

  • We used the position argument to position the object.

  • <AmbientLight> is used to make the color visible; in its absence, the <Box> will look completely black.

Output

It will produce the following output −

raja
Updated on 28-Sep-2021 12:00:05

Advertisements