javascript / intermediate
Snippet
Forwarding Refs to Child Elements
React.forwardRef allows components to expose their internal DOM nodes to parent components. This is crucial for accessibility, managing focus, or integrating with third-party DOM libraries when using functional components.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const CustomInput = React.forwardRef((props, ref) => (<div className="input-wrapper"><label>{props.label}</label><input ref={ref} {...props} /></div>));function Parent() {const inputRef = React.useRef();const focusInput = () => inputRef.current.focus();return (<><CustomInput label="User Name" ref={inputRef} /><button onClick={focusInput}>Focus Input</button></>);}
react
Breakdown
1
React.forwardRef((props, ref) => ...)
A higher-order function that provides the ref as the second argument to the component function.
2
<input ref={ref} />
Attaches the forwarded ref to the actual DOM element so the parent can access it.