Three.js + React. Can I implement Three.js as component in React

I understand that you can implement Three.js as component using three library.

My question is whether I can make Three.js component (let’s say a cube animation) to show in my website that was fully build in React. It seems like Three.js’s canvas always takes 100% of screen.

Is it possible to make it tiny to manipulate like you would do to an img tag? I can’t seem to find the answer. Every Three.js implementation starts with a whole canvas being made of Three.js.

Sorry if the question is foolish. Thank you in advance.

You can define any dimensions for the canvas you like: Edit fiddle - JSFiddle - Code Playground

1 Like

I can’t seem to adjust the width and height with react-three-fiber library as they do not provide render function.

the canvas fills its absolute/relative parent. scale the parent, it scales the canvas with a resize-observer. here’s a demo using the canvas scaled to 200/200px and a spinning cube: Basic demo (forked) - CodeSandbox

there is a render function as well: React Three Fiber Documentation this one is sized manually.

generally you can consider three an imperative system that’s cut off from the declarative world. r3f fixes that. but it’s not a wrapper that you have to rely on, it’s a custom renderer, it reconciles threejs just like react-dom reconciles html, <mesh /> simply becomes new THREE.Mesh(), just like <div /> becomes document.createElement('div').

Can you recommend any other libraries for 3d animation with React? I’m tired of animating SVG’s and they have their limits as well.

lerping is easy and fast, looks a bit bland: Camera pan - CodeSandbox

react-spring has real spring physics: React Three Fiber Documentation

const props = useSpring({ scale: active ? 1.5 : 1 })
return (
  <a.mesh {...props}>
    <boxGeometry />
    ...

basically you can use anything the eco system has to offer. you treat meshes the same way you’d treat a div.