Use three.js with React to build modern sites with 3D graphics

Over the last couple of weeks, I’ve been in the process of revamping my personal site to coincide with the release of some new content. Here’s the final result. I’ve been really loving the look of three.js and was committed to integrating it into the site.


Option One — Using packages and React hooks

After you clone down and start that repo you should see a 3D box that you can interact with and resize by clicking and dragging.

What I love about this package is that even though the canvas is still its own stand-alone element, we now have the capability to interact with the three.js library through state management. The way this is achieved is by returning the mesh method from three.js, which has been appended onto the animation attribute from React Spring. Having this setup means we can dynamically affect different attributes of the library with the inbuild mouse events.

With this option, we are appending the canvas to our application with the useRef hook, which lets us create mutable variables inside functional components. If you’ve never used React refs before they are a great way to access DOM nodes or React elements, but it must be done within a functional component.

Options two — a lighter package free approach

This time our entry point will be a class component inside the componetDidMount lifecycle method.

Here’s what your canvas manager could look like:

I really like this approach because it makes our code more modular and organized. The next steps would be to create your subject matter and then lighting.

Working with three.js is really exciting. There is, however, a substantial amount to take in given the nature of 3D graphics and the intricacies they involve. I’ve just covered a couple of ways to get you started within a React setting, but to get something truly awesome on the screen I’d recommend having a solid understanding of this library and its capabilities by checking out the official docs.

The author of this tutorial is Kahil Nayton, a Brooklyn based full stack developer.

Full stack developer based out of Brooklyn, NYC.

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