What does the ... do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
javascriptreactjsspread-syntax
What does the ... do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
Best Solution
That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).
{...this.props}spreads out the "own" enumerable properties inpropsas discrete properties on theModalelement you're creating. For instance, ifthis.propscontaineda: 1andb: 2, thenwould be the same as
But it's dynamic, so whatever "own" properties are in
propsare included.Since
childrenis 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 achildrenproperty 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.foowith a new object with all the same properties asfooexcept theaproperty, which becomes"updated":