Passing down props using spread operator

suggest change

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 can use the JSX spread ... (an object spread, not only the ES6 array spread) to pass down all of the values. The component will now look like this.

var component = <Component {...this.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'

You can also use the spread operator to pass only some of the props to child components, after destructuring them.

This is useful when child components need many props but you do not want to 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'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents