It’s probably that if you are reading this, you saw the amazing examples using Three.js and react together, but maybe didn’t found a simple and clear steps how to start, so this is for you 💙.
In this section we will:
- Create React App
- Install dependencies
- Create React Component for Three.js
- Import/Use React component with Three.js
- Resources
Before you start
You will need to have the following installed or configured, and know at least the basics of using them, before proceeding
- NodeJS installed (preferable > 12)
- Basic Knowologe in React
- Previous use of
create-react-app
Create React App
npx create-react-app cra-threejs
npm run start
- If everything woks as expected you can navigate to: http://localhost:3000/ and you will see a React App
Install dependencies
Install three.js
package
npm i three
Create React Component for Three.js
- Create a new file for your new component and called it
Three.js
under src folder - Copy the following in the created
Three.js
file - What we are doing here:
- import
three.js
into the app - Use
useEffect
to render the scene for ourthree.js
component - We are using useRef because we want to mount our
three.js
component in the component we are creating and not in the body document, like it’s showed in thethree.js
documentation
- import
import * as THREE from 'three';
import { useEffect, useRef } from "react";
function MyThree() {
const refContainer = useRef(null);
useEffect(() => {
// === THREE.JS CODE START ===
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// document.body.appendChild( renderer.domElement );
// use ref as a mount point of the Three.js scene instead of the document.body
refContainer.current && refContainer.current.appendChild( renderer.domElement );
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}, []);
return (
<div ref={refContainer}></div>
);
}
export default MyThree
- Reference took from here with minor change to make it work with React
Import/Use React component with Three.js
- In the open the file: /src/App.js
- Import your created component adding inthe top pf your file
import Three from './Three';
- Use your componet inside App component:
<Three />
- Boom, if every thing as expected you should see the following in your browser
Resources
- Link to github repo for a working example
- Create React App
- threejs.
Thanks for reading
Top comments (1)
It always amazes me how cluttered React syntax has become.