How to Use Spread Operator with Props in React
In React, you can use the
spread operator (...) to pass all properties of an object as props to a component. This lets you write <Component {...props} /> to forward all props at once instead of listing them individually.Syntax
The spread operator ... is used inside JSX to pass all key-value pairs of an object as props to a component. For example, <MyComponent {...props} /> means each property in the props object becomes a separate prop on MyComponent.
This is useful to forward many props without writing each one manually.
jsx
const props = { title: 'Hello', count: 5 }; <MyComponent {...props} />
Example
This example shows a parent component passing multiple props to a child component using the spread operator. The child receives and displays the props.
jsx
import React from 'react'; function Child(props) { return ( <div> <h2>{props.title}</h2> <p>Count: {props.count}</p> </div> ); } function Parent() { const data = { title: 'Welcome', count: 10 }; return <Child {...data} />; } export default Parent;
Output
<div><h2>Welcome</h2><p>Count: 10</p></div>
Common Pitfalls
- Overwriting props: If you spread props and then add a prop with the same name, the last one wins. For example,
<Component {...props} title="New" />will use "New" fortitle. - Passing unwanted props: Spreading an object with extra keys can send unwanted props to DOM elements, causing React warnings.
- Readability: Overusing spread can make it harder to see which props a component receives.
jsx
const props = { title: 'Old Title', count: 5 }; // Overwrites title prop <MyComponent {...props} title="New Title" />
Quick Reference
Use the spread operator to:
- Pass all props from an object easily.
- Override specific props by adding them after the spread.
- Avoid passing unwanted props to native HTML elements.
Key Takeaways
Use
{...props} in JSX to pass all object properties as props to a component.Props listed after the spread operator override those inside the spread object.
Avoid spreading objects with extra keys onto native HTML elements to prevent warnings.
Spread operator improves code brevity but use it carefully for clarity.
Always check which props are passed when using spread to avoid bugs.