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}>
That's property spread notation. It was added in ES2018, but long-supported in React projects via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).
{...this.props}
spreads out the "own" properties inprops
as discrete properties on theModal
element you're creating. For instance, ifthis.props
containeda: 1
andb: 2
, thenwould be the same as
But it's dynamic, so whatever "own" properties are in
props
are included.Since
children
is an "own" property inprops
, spread will include it. So if the component where this appears had child elements, they'll be passed on toModal
. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting achildren
property in the opening tag. Example:Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:
That replaces
this.state.foo
with a new object with all the same properties asfoo
except thea
property, which becomes"updated"
:Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.
Such as :
The three dots represent the Spread Operator in ES6. It allows us to do quite a few things in Javascript:
Copying an array
Destructuring an array
Function arguments as array
The above is known as rest parameters and does not restrict the number of values passed to a function. However, the arguments must be of the same type.
Combing two objects
... is usually called spread operator , it is use to expand where ever it is required
example
you can use this where ever you requires it more about spread operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
As you know
...
are called Spread Attributes which the name represents it allows an expression to be expanded.And in this case(I'm gonna simplify it).
This:
is equal to
So in short, it's a neat short-cut, we can say.
The three dots
(...)
are called the spread operator, and this is conceptually similar to the ES6 array spread operator, JSX taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSXReference:
1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties
2) https://facebook.github.io/react/docs/jsx-spread.html