How to Render Blender 3D Models in React with React Three Fiber
Click, hover, pinch/zoom, drag me! The 3D model above was created in Blender and imported using React Three Fiber.
More importantly, if you are building web applications using a framework based on React (e.g., this website which is built on Gatsby), you can use React Fiber to render 3D models.
P.S. I made a version of the popular donut tutorial by Andrew Price and imported it into this blog post as a React component (above).
You can do this in 3 simple steps.
Step 1: Export your 3D Model as GLTF 2.0
In Blender, go to file > export > glTF 2.0. If you want to export a specific mesh from your scene, in the export window, select include > Selected objects. In my experiments, mesh objects that are manually added to the scene are straighforward to export correctly; programmatically added objects are more tricky to deal with. In addition, objects with modifiers that have not been applied might not export correctly.
Also, here is an animation of the donut in Blender, in its full 3D glory.
Step 2: Install Three.js and React Three Fiber
npminstall three @react-three/fiber
Reach Three Fiber is a React renderer library for three.js. It brings all the power of three.js merged with all the reasons we love React (reusable components, state) .. with zero performance overhead (according to the author).
Step 3: Import the GLTF 2.0 model into your React app
The code snippet below shows a React component that loads a gltf 2.0 (extension .glb) model and renders it.
The React Component above sets up some ambient lighting <ambientLight/>, a spot light <spotLight/>, and a point light <pointLight/>. <OrbitalControls/> is a component from React Three that allows the user to pan and zoom the scene. With very little code, we have some cool functionality!