Sub topic 11
Passing refs to child components
A parent often needs to focus an input or scroll an element that lives inside a child component. This chapter covers how a ref gets from the parent to a DOM node inside the child. It assumes you can attach a ref to a DOM element with useRef, you know that ref.current is null until the component mounts, and you are comfortable with function components and props.
Why `ref` is not a normal prop
Put ref on a DOM element and React fills ref.current with the node. Put it on your own component and you might expect it to arrive in props.ref. In React 18 and earlier it does not. React treats ref (like key) as a reserved name and removes it before building the props object.
Without extra work, this code does nothing useful in React 18:
function TextInput(props) {
return <input {...props} />;
}
function Form() {
const inputRef = useRef(null);
return <TextInput ref={inputRef} />; // inputRef.current stays null
}React logs a warning that function components cannot be given refs, and inputRef.current stays null. React does not guess which inner element you meant. You have to choose one and pass the ref to it explicitly.
Forwarding with `forwardRef` (React 18 and earlier)
forwardRef wraps a component so it receives the parent's ref as a second argument, after props. You then attach that ref to whichever inner element should be exposed.
import { forwardRef, useRef } from 'react';
const TextInput = forwardRef(function TextInput({ label, ...rest }, ref) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
});
export function SignupForm() {
const emailRef = useRef(null);
return (
<form>
<TextInput label="Email" ref={emailRef} />
<button type="button" onClick={() => emailRef.current.focus()}>
Focus email
</button>
</form>
);
}emailRef.current is the <input> DOM node, not the TextInput component. A component has no handle of its own, so the ref resolves to whatever DOM node the child attaches it to.
Two details are easy to miss:
- The destructuring
{ label, ...rest }keepslabelout of the props spread onto<input>, which would otherwise put a straylabelattribute on the element. - The ref argument is
nullwhen the parent passes no ref. Attachingref={null}is harmless.
`ref` as a prop in React 19
React 19 lets function components read ref as an ordinary prop. You no longer need forwardRef:
import { useRef } from 'react';
function TextInput({ label, ref, ...rest }) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
}
export function SignupForm() {
const emailRef = useRef(null);
return (
<form>
<TextInput label="Email" ref={emailRef} />
<button type="button" onClick={() => emailRef.current.focus()}>
Focus email
</button>
</form>
);
}The parent code is identical. Only the child changed. Because ref is now in props, you can also pass it along with {...props}, which makes thin wrappers shorter.
| Question | React 18 and earlier | React 19 |
|---|---|---|
| How does a function component get the ref? | Second argument of `forwardRef` | Regular `ref` prop |
| Is `forwardRef` needed? | Yes | No, and it is slated for deprecation |
| Does old `forwardRef` code still work? | Yes | Yes |
| Does `ref` appear in `props`? | No | Yes |
Check your installed React version before choosing a style. A library that must support both versions should keep using forwardRef.
How the ref travels
The ref object itself never changes. The parent creates one object, and each layer hands the same object down until an element receives it.
The timing rules from earlier chapters still apply. The parent sees null during its first render. It should read ref.current only in event handlers and effects, never while rendering.
Forwarding through several layers
Each component between the parent and the DOM node has to forward the ref. If one layer drops it, the chain ends there and ref.current stays null.
import { forwardRef } from 'react';
const Field = forwardRef(function Field({ label, ...rest }, ref) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
});
const PasswordField = forwardRef(function PasswordField(props, ref) {
return <Field label="Password" type="password" ref={ref} {...props} />;
});PasswordField is a thin wrapper, but it still has to accept ref and pass it to Field. Without that, a parent's ref on PasswordField would stop at PasswordField.
Edge cases and gotchas
Wrappers that hide the ref
Higher-order components and React.memo need care. memo(forwardRef(...)) works, and so does forwardRef(memo(...)), but a custom higher-order component that returns a new component swallows the ref unless it forwards it. If a ref goes missing, look for a wrapper that does not pass it along.
The ref is `null` when the target is not rendered
If the child renders the input conditionally, ref.current is null while it is hidden. It also returns to null when the element unmounts. Guard your calls when the element might not exist:
function focusIfPresent(ref) {
ref.current?.focus();
}Class components
Putting ref on a class component gives you the class instance, not a DOM node. Forwarding through forwardRef or a ref prop is the way to reach a DOM node inside a function component.
Callback refs work too
The ref you receive can be a function instead of an object, because the parent may have passed a callback ref. Pass it straight through to the element, as above. Do not read ref.current on it, since a function has no current. In React 19, a callback ref may return a cleanup function, which React calls when the element is removed.
Do not forward to the wrong element
Forward the ref to the element a caller would expect, usually the interactive one. For TextInput, that is the <input>, not the wrapping <label>. A caller who writes ref.current.focus() expects focus to land somewhere useful.
Expose less than the whole node
Forwarding a ref gives the parent full access to the DOM node. The parent can call focus(), but it can also change style, read value, or remove the element. That coupling makes the child hard to refactor, because the parent may depend on its internal markup.
When you want the parent to do only a few specific things, use useImperativeHandle to expose a small object such as { focus } instead of the node. The next chapters cover that API. For simple input wrappers, plain forwarding is usually enough.
Quick checklist
- Create the ref in the parent with
useRef(null). - Pass it as
ref={...}on the child component. - In the child, accept it (second argument in React 18,
refprop in React 19). - Attach it to the one DOM element you intend to expose.
- In every wrapper layer in between, forward it again.
- Read
ref.currentonly in handlers and effects, and guard fornull.
Exercise
In React 18, a parent writes <Card ref={cardRef} />, where Card is function Card({ title }) { return <section><h2>{title}</h2></section>; }. Clicking a button runs cardRef.current.scrollIntoView() and throws "Cannot read properties of null". What is wrong, and how do you fix it?
Show answer
Card is a plain function component, so React does not pass ref to it and cardRef.current stays null. Wrap Card in forwardRef, accept ref as the second argument, and attach it to the <section>: const Card = forwardRef(function Card({ title }, ref) { return <section ref={ref}><h2>{title}</h2></section>; });. In React 19, destructure ref from the props instead and attach it to the <section>, with no forwardRef.
Exercise
PasswordField renders <Field label="Password" type="password" /> and Field correctly forwards its ref to an <input>. A parent puts ref={pwRef} on PasswordField, but pwRef.current is null after mount. Why, and what is the minimal change?
Show answer
PasswordField does not accept or forward the ref, so the chain stops there. Make PasswordField accept the ref (with forwardRef, or as a ref prop in React 19) and pass it on as <Field ref={ref} ... />.