Sub topic 10
Forwarding props with the spread syntax
This chapter assumes you can write function components, destructure objects in JavaScript, and pass props with curly braces. It covers how to collect the props a component doesn't use itself and pass them to another element.
The problem: wrapper components
Suppose you wrap a native <input> to add a label. The input accepts dozens of attributes, such as type, placeholder, value, disabled, and onChange. Listing each one in your wrapper would be tedious and would break whenever you needed another attribute.
The rest pattern and the spread syntax solve this. Both use ..., but they do opposite jobs.
- Rest in a parameter list collects the remaining properties into a new object.
- Spread in JSX expands an object into separate attributes.
function TextInput({ label, ...rest }) {
return (
<label>
{label}
<input {...rest} />
</label>
);
}
<TextInput label="Email" type="email" placeholder="[email protected]" />label is pulled out because the wrapper uses it. Everything else (type and placeholder) lands in rest. The expression <input {...rest} /> is equivalent to writing <input type="email" placeholder="[email protected]" />.
Order decides who wins
When the same prop appears twice, the later one wins. This lets you choose between a default and a forced value.
function Button({ children, ...rest }) {
return (
<button type="button" {...rest}>
{children}
</button>
);
}
function SubmitButton({ children, ...rest }) {
return (
<button {...rest} type="submit">
{children}
</button>
);
}In Button, the caller can override type because the spread comes after it. In SubmitButton, the type is always submit because it comes after the spread.
Merging instead of overriding
Spreading replaces a prop outright. If both you and the caller want to set className, the spread order means one of you loses. Destructure the prop and combine the values yourself.
function Badge({ className = '', children, ...rest }) {
return (
<span className={`badge ${className}`.trim()} {...rest}>
{children}
</span>
);
}
<Badge className="badge-warning" title="Needs review">New</Badge>Because className was removed from rest, the spread can't overwrite the merged value. The same approach works for style and for event handlers. If you need to run both your handler and the caller's, call each one inside a single function.
Spreading a whole object
You can also spread an object you build yourself.
const inputProps = { type: 'password', required: true, minLength: 8 };
<TextInput label="Password" {...inputProps} />This helps when the same set of props is reused in several places, for example props returned from a form library.
Gotchas
- Unknown props reach the DOM. If a parent passes
variant="primary"and you forwardrestto a<div>, React warns about an unknown DOM attribute. Destructure props that are meant for your own logic so they never enterrest. - Spreading hides the interface. A reader can't tell which props a component accepts by reading its signature. Use spread for thin wrappers around a single element, and prefer explicit props for components with their own behavior.
- Spread is shallow. It copies top-level properties only. A nested
styleobject is passed by reference, not merged. keyis not part of props. React reads it and removes it, so it never appears inrest.
Exercise
A component is declared as function Tag({ color, ...rest }) { return <span style={{ color }} {...rest} />; }. A parent renders <Tag color="red" style={{ fontWeight: 'bold' }} />. What does the span's text look like, and how would you fix it so it is both red and bold?
Show answer
The span is bold but not red. style is in rest, and spreading it after the style attribute replaces the object that contained color. To fix it, destructure style as well and merge: function Tag({ color, style, ...rest }) { return <span style={{ color, ...style }} {...rest} />; }.