What does the ...
do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
What does the ...
do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
It's just defining props in a different way in JSX for you!
It's using
...
array and object operator in ES6 (object one not fully supported yet), so basically if you already define your props, you can pass it to your element this way.So in your case, the code should be something like this:
so the props you defined, now separated and can be reused if necessary.
It's equal to:
These are the quotes from React team about spread operator in JSX:
This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:
And with an object/keys:
What's really cool is you can use it to mean "the rest of the values".
This is a feature of es6 which is used in React as well. Look at the below example:
This way is fine if we have maximum 3 parameters but what if we need to add for example 110 parameters. Should we define them all and add them one by one?! Of course there is an easier way to do which is called SPREAD. Instead of passing all those parameters you write :
We have no idea how many parameters we have but we know there are heaps of those. Based on es6 we can rewrite the above function as below and use the spread and mapping between them to make it as easy as a piece of cake: