Using Three.js to make a 3D Scene in React.js

Photo by Amarnath Tade on Unsplash
//> npx create-react-app three-js-intro
//> cd three-js-intro
//> npm install three
// ... App.jsimport React from "react";
import ReactDOM from "react-dom";
import * as THREE from "three";
class App extends Component {
render() {
return (
<div />
)
}
}
const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement);
export default App;
// ... App.jsimport React from "react";
import ReactDOM from "react-dom";
import * as THREE from "three";
class App extends Component {
componentDidMount() {
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 );
this.mount.appendChild( renderer.domElement );

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshStandardMaterial( { color: 0x7e31eb } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube ); const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
scene.add( light );
camera.position.z = 2;var animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
cube.rotation.z += 0.01;
renderer.render( scene, camera );
};
animate();
}
render() {
return (
<div ref={ref => (this.mount = ref)} />
)
}
}
const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement);
export default App;

Software Engineer and Brazilian Jiu-Jitsu brown belt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store