Sub topic 10
Forwarding props with the spread syntax
This chapter assumes you can write function components, pass props, and use object destructuring and default values. It also assumes you know the difference between a component like TextInput and a DOM element like input. You don't need TypeScript until the typing section.
What the spread syntax does in JSX
JSX lets you spread an object into an element's attributes with {...object}. Each key becomes a prop name and each value becomes that prop's value.
const buttonProps = { type: 'submit', disabled: false, 'aria-label': 'Save' };
function SaveButton() {
return <button {...buttonProps}>Save</button>;
}This is the same as writing the props out by hand:
<button type="submit" disabled={false} aria-label="Save">Save</button>The spread is not a React feature. It is object spread, the same syntax as { ...a, ...b } in plain JavaScript, applied to the props object that JSX builds. This explains the rules for ordering and conflicts later in the chapter.
Collecting and forwarding with the rest pattern
Spreading is most useful with its counterpart, the rest pattern in a parameter list. Rest collects every prop you did not name into one object. You can then spread that object onto an inner element.
function TextInput({ label, ...rest }) {
return (
<label>
{label}
<input {...rest} />
</label>
);
}
export default function App() {
return (
<TextInput
label="Email"
type="email"
placeholder="[email protected]"
required
/>
);
}TextInput uses label itself. It never mentions type, placeholder, or required, yet all three reach the input. If you later need autoComplete or onBlur, callers can pass them and the component needs no change.
This pattern is common in design-system components such as buttons, inputs, and cards. These are thin wrappers around a native element, and callers expect them to accept every attribute the native element does.
Order decides who wins
Later props override earlier ones, whether they are written as attributes or spread. Where you put {...rest} therefore decides who has the final say.
| Placement | Who wins | Typical use |
|---|---|---|
| `<input type="text" {...rest} />` | The caller. A `type` in `rest` replaces `"text"`. | Sensible defaults the caller may change |
| `<input {...rest} type="text" />` | The component. Any `type` in `rest` is ignored. | Values the component must control |
A button wrapper shows both choices:
function PrimaryButton({ className = '', ...rest }) {
return (
<button
type="button"
{...rest}
className={`btn btn-primary ${className}`.trim()}
/>
);
}Here type="button" is a default, so a caller can pass type="submit". The className is placed after the spread because it must be merged. If you left className inside rest and put the spread last, a caller's class would replace btn btn-primary instead of adding to it.
The same applies to style, which is an object. If the component and the caller both supply styles, merge them yourself with style={{ ...baseStyle, ...style }}. JSX does not merge them for you.
Wrapping event handlers
Handlers need special care. If the component adds its own onClick and spreads rest afterward, the caller's onClick silently replaces yours. If you spread first, yours silently replaces the caller's. Pull the handler out of rest and call both:
function TrackedButton({ onClick, ...rest }) {
function handleClick(event) {
console.log('button clicked');
onClick?.(event);
}
return <button type="button" {...rest} onClick={handleClick} />;
}The optional call onClick?.(event) keeps the component working when the caller passes no handler.
Forwarding children
children is an ordinary prop, so it is part of rest unless you destructure it. In PrimaryButton above, a caller writes <PrimaryButton>Save</PrimaryButton> and rest.children is "Save". Spreading rest onto button forwards it, which is why the element can be self-closing.
Be careful if you spread rest and also write explicit children inside the element. Explicit children in JSX are applied after the spread and replace rest.children. That is correct when you intend it. It is a bug when you forgot that children was in rest.
Things that go wrong
Unknown props reach the DOM
If you forward everything, you also forward props that your component meant for itself. React passes unknown props on a native element to the DOM, and in development it warns about them.
function Box({ highlighted, ...rest }) {
return (
<div
{...rest}
className={highlighted ? 'box box-on' : 'box'}
/>
);
}Because highlighted is destructured, it stays out of rest. If you wrote function Box(props) and spread props, highlighted would land on the div. React would warn about a non-boolean attribute or an unknown prop, depending on the value. The rule is to name every prop your component consumes, then forward only what remains.
Spreading hides the component's API
function Card(props) followed by <div {...props} /> tells a reader nothing about what Card accepts. Reviewers must read the callers to learn the contract. Prefer named props for anything the component depends on, and use rest forwarding only for the open-ended "any valid attribute" part. TypeScript helps here, as shown below.
Unwanted overrides
Spreading user-controlled data is risky. If an object from a form or an API response is spread onto an element, a key like dangerouslySetInnerHTML or href: "javascript:..." would be applied as-is. Spread only objects whose keys you control, or pick the fields you want explicitly.
`key` and `ref`
key is not a real prop. React reads it during rendering and does not put it in the props object, so a component never sees it in rest. If you spread an object that contains a key into JSX, recent React versions warn. Write the key as an explicit attribute and spread the rest:
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
function NameList() {
return (
<ul>
{rows.map(({ id, ...itemProps }) => (
<li key={id} {...itemProps} />
))}
</ul>
);
}This example spreads name onto each li, which would be an unknown attribute in a real app. Treat it as a demonstration of where key goes.
ref depends on your React version. In React 19, function components receive ref as a normal prop, so it travels through rest to the inner element. In React 18 and earlier, ref is not in props at all. A wrapper must use forwardRef to pass it down. Check your version before relying on rest to carry a ref.
Typing forwarded props in TypeScript
In TypeScript, you don't need to list every attribute of the native element. Reuse React's type for that element and add your own props.
import type { ComponentPropsWithoutRef } from 'react';
type TextInputProps = ComponentPropsWithoutRef<'input'> & {
label: string;
};
export function TextInput({ label, ...rest }: TextInputProps) {
return (
<label>
{label}
<input {...rest} />
</label>
);
}ComponentPropsWithoutRef<'input'> includes type, placeholder, onChange, and the rest of the input attributes, so the compiler checks what callers forward. Use ComponentPropsWithoutRef when your component does not forward refs, and ComponentProps when ref is part of the props. If your own prop name clashes with a native one, use Omit<ComponentPropsWithoutRef<'input'>, 'size'> & { size: number } to avoid an impossible intersection.
When not to spread
Choose explicit props when the component has a small, fixed set of inputs. Choose rest forwarding when the component is a thin wrapper that should behave like its inner element. If you find yourself spreading through several layers, ask whether the intermediate components need to know about those props at all. Composition with children or slot props is often clearer.
Exercise
In this component, a caller renders <Field type="password" />. What type does the input get, and how would you change the component so it always renders type="text"?
function Field({ ...rest }) {
return <input type="text" {...rest} />;
}
Show answer
The input gets type="password", because {...rest} comes after type="text" and later props override earlier ones. To lock the value, move the spread first: <input {...rest} type="text" />.
Exercise
You are writing a Link wrapper that adds rel="noopener noreferrer" and logs each click, while still accepting any attribute of an a element. Which props should you pull out of rest, and why?
Show answer
Pull out onClick, so you can call it from your own handler instead of letting one handler replace the other. Pull out rel too if you want to merge it with the caller's value, or place rel after the spread if it must always be set. Everything else (href, target, className, and so on) can stay in rest and be spread onto the a.