1

I'm trying to figure out how I can get the scene object programatically in React Three Fiber, so that I can add a Three component in the traditional way: scene.add(myThing). I've tried using const canvasRef = useRef() with <Canvas ref={canvasRef} /> but the ref seems to be undefined when passing to another Component.

I know this is probably really bad practice, but what I'm trying to do, is convert this for use in React Three Fiber, but Geometry has been replaced with BufferGeometry and I'm a bit lost. I found this, but as mentioned, I'm just trying to use scene.add() for now until I can figure more out about the inner workings of Three.

Thanks for any help.

timhc22
  • 7,213
  • 8
  • 48
  • 66

3 Answers3

0

You can use the useThree provided by React Three Fiber.

https://docs.pmnd.rs/react-three-fiber/api/hooks

TimL
  • 1
0

I had the same issue in one of my project and i went for this using Three.js and three fiber :

import { useThree } from "@react-three/fiber"
import { BoxGeometry, Mesh, MeshStandardMaterial } from "three";

  const { scene } = useThree()

  const addThreeComponent = () => {
    const geometry = new BoxGeometry(100, 10, 100);
    const material = new MeshStandardMaterial({ color: 0x00ff00 });
    const newBox = new Mesh(geometry, material);
    newBox.position.set(0, 10, 0);
    scene.add(newBox);
  }
victorchtl
  • 13
  • 3
0

Ended up implementing forwardRef myself.

const ThreeForwardRef = forwardRef(props, ref) => {
   const { scene, camera } = useThree();
   useImperativeHandle(ref, () => ({
      scene,
      camera,
   }), [scene, camera]);
}

export const MyCanvas = forwardRef(({ children }, ref) => {
   return (
      <Canvas>
         <ThreeForwardRef ref={ref} />
         { children }
      </Canvas>
   );
}

Usage:

const ref = useRef();
// ref.current.scene;

<MyCanvas ref={ref}>
   ...
<MyCanvas />
kitta
  • 1,723
  • 3
  • 23
  • 33