Forwarding Refs to Nested Components
You'll learn how to pass refs through multiple layers of components and when to forward versus expose custom methods.
The Nested Component Challenge
When you wrap a component inside another component, forwardRef gets the ref to your wrapper — but what if the actual DOM node you need is buried deeper? You need to forward the ref again through each layer until it reaches the target element.
Think of it like passing a package through a chain of people: each person (component layer) needs to explicitly hand it to the next person, not just hold onto it.
Forwarding Through Multiple Layers
const Input = forwardRef<HTMLInputElement>((props, ref) => {
return <input ref={ref} {...props} />;
});
const FormField = forwardRef<HTMLInputElement>((props, ref) => {
// Forward the ref to the nested Input component
return (
<div className="field">
<label>Name:</label>
<Input ref={ref} />
</div>
);
});
function App() {
const inputRef = useRef<HTMLInputElement>(null);
return <FormField ref={inputRef} />;
}
Each wrapper uses forwardRef and passes ref down to the next component until it reaches the actual DOM element.
Forward vs Expose: Making the Choice
Sometimes you don't want to expose the raw DOM node. Instead, expose only specific methods using useImperativeHandle:
const FormField = forwardRef((props, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focusAndClear: () => {
inputRef.current?.focus();
inputRef.current!.value = '';
}
}));
return <Input ref={inputRef} />;
});
When to forward: The parent needs full DOM access (measuring, scrolling).
When to expose: You want to control which operations are allowed (encapsulation).
Key Takeaway: Refs must be explicitly forwarded through each component layer using forwardRef, or you can use useImperativeHandle to expose only specific methods instead of the raw DOM node.