Skip to content

forwardRef

Description

Sometimes you want to reference your custom function component from the parent component that uses it.

For example, if you had a function component named Box, and you wanted to reference it in the parent component, then you may try to use a useRef for the purpose.

E.g.,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Canvas } from '@react-three/fiber'
import { useRef } from 'react'
import { useFrame } from '@react-three/fiber'

function Box(props) {
  const ref = useRef()

  useFrame((_, delta) => {
    ref.current.rotation.x += 1 * delta
    ref.current.rotation.y += 0.5 * delta
  })

  return (
    <mesh {...props} ref={ref}>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
}

export default function App() {
  const ref = useRef()

  return (
    <Canvas camera={{ position: [0, 0, 2] }}>
      <Box ref={ref} />
    </Canvas>
  )
}

The above code will throw an error suggesting to use React.forwardRef.

Error

Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?

The code below is the same example from above, but re-written to use React.forwardRef

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Canvas } from '@react-three/fiber'
import { useRef, forwardRef } from 'react'
import { useFrame } from '@react-three/fiber'

const Box = forwardRef(function Box(props, ref) {
  useFrame((_, delta) => {
    ref.current.rotation.x += 1 * delta
    ref.current.rotation.y += 0.5 * delta
  })

  return (
    <mesh {...props} ref={ref}>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
})

export default function App() {
  const ref = useRef()

  return (
    <Canvas camera={{ position: [0, 0, 2] }}>
      <Box ref={ref} />
    </Canvas>
  )
}
Forwarding Refs reactjs.org

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout forwardRef
npm install
npm start

Comments