How to make a cylinder in React using reactthree-fiber

React JSJavascript LibraryFront End Technology

In this article, we will see how to create a basic cylinder-like shape in React using 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.


First download 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. Three-fiber will be used to connect threejs and React.

Add the following lines of code in App.js

import React, { useEffect, useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import * as THREE from "three";
function Cylinder() {
   const myref = useRef();

   useFrame(() => (myref.current.rotation.x = myref.current.rotation.y += 0.01));

   return (
      <mesh ref={myref}>
         <cylinderBufferGeometry attach="geometry" args={[2, 2, 2]} />
         <meshBasicMaterial attach="material" color="hotpink" />

export default function App() {
   return (
         <ambientLight />
         <Cylinder />


Here we simply created cylinder geometry and mesh for coloring. Always use a separate function to make a shape and then render it inside canvas. The Cylinder function takes 3 arguments: top radius, bottom radius, and height.

<mesh> is used to create the threeJS object, and inside it, we made a box using CylinderGeometry which is used to define the size, shape, and other structural properties. 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 made a Frame which is required to change the position of our mesh object or cylinder. Then 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 <Cylinder> will look completely black.


On execution, it will produce the following output −

Published on 28-Sep-2021 12:12:36