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.
Passing React Props Using the Spread Operator in JSX According to the React docs: You can spread the props attributes to pass it in JSX using the Spread operator which passes the whole props object. So when your intent is to pass the whole props object, that's fine to use!
Now you can use a new feature of JSX called spread attributes. The properties of the object that you pass in are copied onto the component's props. You can use this multiple times or combine it with other attributes. The specification order is important.
The Spread operator lets you expand an iterable like an object, string, or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With