Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding JSX spread operator [duplicate]

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.

like image 650
ffxsam Avatar asked Sep 02 '15 22:09

ffxsam


People also ask

How do you use the spread operator in JSX?

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!

How would you use component spread attributes in JSX?

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.

How spread works in react?

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.


1 Answers

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

like image 91
pherris Avatar answered Sep 29 '22 20:09

pherris