0

I am trying to access OrbitControls ref as follow:

const controlsRef = useRef<any>();

  return (
    <>
      <Canvas
        camera={{
          position: [0, 0, 100],
          up: [0, 0, 1],
        }}
      >
        <OrbitControls makeDefault ref={controlsRef} />
        <ambientLight />
        <FakeSphere position={[0, 0, 0]} color="red" />
        <FakeSphere position={[100, 100, 0]} color="blue" />
        <Nav controls={controlsRef.current} />
      </Canvas>
    </>
  );

Code: https://codesandbox.io/s/cool-flower-f5qr0?file=/src/App.tsx:949-962

The ref is undefined. Any idea please?

beewest
  • 4,486
  • 7
  • 36
  • 63

1 Answers1

0

Found a hint hehe (https://github.com/pmndrs/drei/issues/718). Cant get ref from outside Canvas.

For now, add a wrapper over OrbitControls to capture the ref. Not sure if any better solution or not.

const MyControls = (props: any) => {
  const { setControls } = props;
  const ref = useRef<any>();

  useEffect(() => {
    if (!ref.current) return;
    setControls(ref.current);
  }, ref.current);
  return <OrbitControls makeDefault ref={ref} />;
};
beewest
  • 4,486
  • 7
  • 36
  • 63