ffxsam ffxsam - 11 days ago 6
React JSX Question

Trouble understanding JSX spread operator

Given this example code from the React docs:

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


I did some looking into what
...props
actually evaluates to, which is this:

React.__spread({}, props)


Which in turn evaluates to
{foo: x, bar: y}
.

But what I'm wondering is, why can't I just do this:

var component = <Component props />;


I don't see understand what the point of the spread operator is.

Answer

This helps make your code more succinct - since props is an object, the spread operator takes the properties of the object you pass in and applied them to the component. So the Component will have properties a foo with a value of x and a bar with a value of y.

It would be the same as:

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

just shorter

Comments