MOCKSTACKS
EN
Questions And Answers

More Tutorials









React Passing down props using spread operator


Instead of
var component = <Component foo={this.props.x} bar={this.props.y} />;

Where each property needs to be passed as a single prop value you could use the spread operator ... supported
for arrays in ES6 to pass down all your values. The component will now look like this.

var component = <Component {...props} />;

Remember that the properties of the object that you pass in are copied onto the component's props.

The order is important. Later attributes override previous ones.

var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
 console.log(component.props.foo); // 'override'

Another case is that you also can use spread operator to pass only parts of props to children components, then you can use destructuring syntax from props again.

It's very useful when children components need lots of props but not want pass them one by one.

const { foo, bar, other } = this.props // { foo: 'foo', bar: 'bar', other: 'other' };
var component = <Component {...{foo, bar}} />;
const { foo, bar } = component.props
 console.log(foo, bar); // 'foo bar'


Conclusion

In this page (written and validated by ) you learned about React Passing down props using spread operator . What's Next? If you are interested in completing React tutorial, your next topic will be learning about: React Props children and component composition.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.