Skip to content


 Zabbix
 Grafana
 Prometheus
 React Three Fiber
 Threejs and TypeScript
 SocketIO and TypeScript
 Blender Topological Earth
 Sweet Home 3D
 Design Patterns Python
 Design Patterns TypeScript
   
 Course Coupon Codes
Three.js and TypeScript
Kindle Edition
$6.99 $9.99 Paperback 
$22.99 $29.99




Design Patterns in TypeScript
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




Design Patterns in Python
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




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