Return to site

⚛️ REACT: 3D animation with Three.JS lib

· react

React Three.js is a library that combines the power of React with Three.js, a popular JavaScript library for creating 3D graphics and animations in the web browser. It allows you to create and manipulate 3D objects and scenes using familiar React components and concepts.

Install the lib with:

 

npm install react-three-fiber

Here's a simple code demo to create a basic 3D cube using React Three.js:

import React, { useRef } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'


function Cube(props) {
  // This reference will give us direct access to the mesh
  const mesh = useRef()


  // Rotate the mesh every frame
  useFrame(() => {
    mesh.current.rotation.x += 0.01
    mesh.current.rotation.y += 0.01
  })


  return (
    <mesh {...props} ref={mesh}>
      <boxBufferGeometry />
      <meshStandardMaterial color="hotpink" />
    </mesh>
  )
}


function App() {
  return (
    <Canvas>
      <ambientLight />
      <pointLight position={[10, 10, 10]} />
      <Cube position={[0, 0, 0]} />
    </Canvas>
  )
}


export default App

In this example, we import the necessary React Three.js components and hooks, and define a Cube component that creates a 3D cube mesh using a boxBufferGeometry and a meshStandardMaterial. We also use the useFrame hook to rotate the cube every frame.

In the App component, we create a Canvas component that provides the WebGL rendering context, and add an ambient light and a point light to the scene. Finally, we add an instance of our Cube component to the scene with a specified position.

This is just a basic example, but React Three.js provides many more features and options for creating complex 3D scenes and animations.