What do these three dots in React do?

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 in props as discrete properties on the Modal element you’re creating. For instance, if this.props contained a: 1 and b: 2, then

<Modal {...this.props} title='Modal heading' animation={false}>

would be the same as

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

But it’s dynamic, so whatever “own” properties are in props are included.

Since children is an “own” property in props, spread will include it. So if the component where this appears had child elements, they’ll be passed on to Modal. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children property in the opening tag. Example:

Show code snippet

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:

this.setState(prevState => {
    return {foo: {...prevState.foo, a: "updated"}};
});

That replaces this.state.foo with a new object with all the same properties as foo except the a property, which becomes "updated":

Show code snippet

Leave a Comment