How to forward refs in React with forwardRef
· Category: React
Short answer
forwardRef lets a component pass a ref it receives to one of its child elements, enabling parent components to directly access DOM nodes or child instances.
Steps
- Wrap your component with
React.forwardRef((props, ref) => ...). - Assign the
refto the desired child element. - Use the ref from the parent as usual.
Example
const FancyInput = React.forwardRef((props, ref) => (
<input ref={ref} className="fancy" {...props} />
));
function Parent() {
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); }, []);
return <FancyInput ref={inputRef} />;
}
Tips
- In React 19+,
forwardRefis being deprecated in favor of passingrefas a normal prop. - Use
useImperativeHandlewithforwardRefto expose a limited API instead of the full DOM node.