javascript / intermediate
Snippet
Forwarding Refs to Child Components
Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is especially useful for highly reusable 'leaf' components like buttons or inputs that need their DOM nodes accessed by parents for focus, selection, or measurements.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { forwardRef, useRef } from 'react';const CustomInput = forwardRef((props, ref) => (<input ref={ref} className="custom-input" {...props} />));function Parent() {const inputRef = useRef(null);const handleClick = () => inputRef.current.focus();return (<><CustomInput ref={inputRef} /><button onClick={handleClick}>Focus Input</button></>);}
react
Breakdown
1
const CustomInput = forwardRef((props, ref) => (
Wraps the component in forwardRef to accept a ref argument alongside props.
2
<input ref={ref} ... />
Attaches the forwarded ref directly to the underlying DOM element.