Last updated: Apr 6, 2024
Reading time·3 min
Use the spread syntax (...) to pass an object as props to a React component,
e.g. <Person {...obj} />
.
The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.
function Person({name, age, country}) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { const obj = {name: 'Alice', age: 29, country: 'Austria'}; return ( <div> <Person {...obj} /> </div> ); }
We used the spread syntax (...) to pass an object's properties as props to a component.
const obj2 = {...{a: 1, b: 2}}; console.log(obj2); // 👉️ {a: 1, b: 2}
Now the Person
component can destructure and use all of the passed props.
If you get the warning prop spreading is forbidden, click on the link and follow the instructions.
If you need to pass an object as props when using React TypeScript, check out the following tutorial.
If you pass the entire object as a prop, you would have to access the properties on the object in the child component.
function Person({data}) { return ( <div> <h2>{data.name}</h2> <h2>{data.age}</h2> <h2>{data.country}</h2> </div> ); } export default function App() { const obj = {name: 'Alice', age: 29, country: 'Austria'}; return ( <div> <Person data={obj} /> </div> ); }
Notice that the Person
component now accesses the properties on the data
object.
You can get around this by destructuring one level deeper in its props object.
function Person({data: {name, age, country}}) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { const obj = {name: 'Alice', age: 29, country: 'Austria'}; return ( <div> <Person data={obj} /> </div> ); }
Now we don't have to access every property on the data
object even though the
parent component passes an entire object as a prop.
If you need to pass an array as a prop, click on the link and follow the instructions.
If your object is not stored in a variable and is passed inline, you would have two sets of curly braces when passing the object as a prop.
function Person({data}) { return ( <div> <h2>{data.name}</h2> <h2>{data.age}</h2> <h2>{data.country}</h2> </div> ); } export default function App() { return ( <div> <Person data={{name: 'Alice', age: 29, country: 'Austria'}} /> </div> ); }
The outer set of curly braces wraps the expression and the inner set is the actual object prop.
You can also pass individual properties of the object as props to the child component.
function Person({name, age, country}) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { const obj = {name: 'Alice', age: 29, country: 'Austria'}; return ( <div> <Person name={obj.name} age={obj.age} country={obj.country} /> </div> ); }
The benefit of doing that is that you can omit some of the object's properties that are not required in the child component.