The Spread Operator with Props
What you'll learn: How to forward multiple props at once using JSX spread syntax, making wrapper components cleaner and more maintainable.
When you build wrapper components (components that wrap other components), you often need to pass many props through to the inner component. You could pass each prop individually, but there's a better way.
The Problem: Prop Forwarding by Hand
Imagine a FancyButton that wraps a regular button but adds some styling. You'd need to manually forward every prop:
function FancyButton({ onClick, disabled, type, children }) {
return (
<button
onClick={onClick}
disabled={disabled}
type={type}
className="fancy"
>
{children}
</button>
);
}
This gets tedious fast. What if you need aria-label? title? You'd keep adding parameters.
The Solution: Spread Syntax
JSX lets you "spread" an object's properties directly onto a component:
function FancyButton({ children, ...otherProps }) {
return (
<button {...otherProps} className="fancy">
{children}
</button>
);
}
// Now this works automatically:
<FancyButton onClick={handleClick} disabled type="submit">
Click Me
</FancyButton>
The ...otherProps captures all props except children, then {...otherProps} spreads them onto the <button>. It's like saying "pass through whatever props I received."
When to Use It
This pattern shines for wrapper components that enhance or style existing components without blocking their functionality. You add your layer while keeping the wrapped component's full API available.
Key Takeaway: The spread operator ({...props}) lets you forward multiple props at once without naming each one, making wrapper components flexible and maintainable.