What do these three dots in React do?

What do these three dots in React do?

What does the … do in this React (using JSX) code and what is it called?

Solutions/Answers:

Solution 1:

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 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:

class Example extends React.Component {
  render() {
    const { className, children } = this.props;
    return (
      <div className={className}>
      {children}
      </div>
    );
  }
}
ReactDOM.render(
  [
    <Example className="first">
      <span>Child in first</span>
    </Example>,
    <Example className="second" children={<span>Child in second</span>} />
  ],
  document.getElementById("root")
);
.first {
  color: green;
}
.second {
  color: blue;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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":

const obj = {
  foo: {
    a: 1,
    b: 2,
    c: 3
  }
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);
.as-console-wrapper {
  max-height: 100% !important;
}

Solution 2:

As you know ... are called Spread Attributes which the name represents it allows an expression to be expanded.

var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

And in this case(I’m gonna simplify it).

//just assume we have an object like this:
var person= {
    name: 'Alex',
    age: 35 
}

This:

<Modal {...person} title='Modal heading' animation={false} />

is equal to

<Modal name={person.name} age={person.age} title='Modal heading' animation={false} />

So in short, it’s a neat short-cut, we can say.

Solution 3:

The three dots in JavaScript are spread / rest operator.

Spread operator

The spread syntax allows an expression to be expanded in places where multiple arguments are expected.

myFunction(...iterableObj);

[...iterableObj, 4, 5, 6]

[...Array(10)]

Rest parameters

The rest parameter syntax is used for functions with variable number of arguments.

function(a, b, ...theArgs) {
  // ...
}

The spread / rest operator for arrays was introduced in ES6. There’s a State 2 proposal for object spread / rest properties.

TypeScript also supports the spread syntax and can transpile that into older versions of ECMAScript with minor issues.

Solution 4:

The three dots represent the Spread Operator in ES6. It allows us to do quite a few things in Javascript:

  1. Copying an array

    var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
    var racingGames = ['Need For Speed', 'Gran Turismo', 'Burnout'];
    var games = [...shooterGames, ...racingGames];
    
    console.log(games)  // ['Call of Duty', 'Far Cry', 'Resident Evil',  'Need For Speed', 'Gran Turismo', 'Burnout']
    
  2. Destructuring an array

      var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
      var [first, ...remaining] = shooterGames;
      console.log(first); //Call of Duty
      console.log(remaining); //['Far Cry', 'Resident Evil']
    
  3. Function arguments as array

     function fun1(...params) { 
    
     }  
    

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.

  1. Combing two objects

    var myCrush = {
      firstname: 'Selena',
      middlename: 'Marie'
    };
    
    var lastname = 'my last name';
    
    var myWife = {
      ...myCrush,
      lastname
    }
    
    console.log(myWife); // {firstname: 'Selena',
                         //   middlename: 'Marie',
                         //   lastname: 'my last name'}
    

Solution 5:

This is a feature of es6 which is used in React as well. Look at the below example:

function Sum(x,y,z) {
   return x + y + z;
}
console.log(Sum(1,2,3)); //6

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 :

function (...numbers){} 

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:

let Sum = (...numbers) => {
return numbers.reduce((prev, current) => prev + current );
}
console.log(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9));//45

Solution 6:

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:

function yourA() {
  const props = {name='Alireza', age='35'};
  <Modal {...props} title='Modal heading' animation={false} />
}

so the props you defined, now separated and can be reused if necessary.

It’s equal to:

function yourA() {
  <Modal name='Alireza' age='35' title='Modal heading' animation={false} />
}

These are the quotes from React team about spread operator in JSX:

JSX Spread Attributes
If you know all the properties that you want to place on a component
ahead of time, it is easy to use JSX:

var component = <Component foo={x} bar={y} />;

Mutating Props is Bad
If you don’t know which properties you want to set, you might be tempted to add them onto the object later:

var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad

This is an anti-pattern because it means that we can’t help you check
the right propTypes until way later. This means that your propTypes
errors end up with a cryptic stack trace.

The props should be considered immutable. Mutating the props object
somewhere else could cause unexpected consequences so ideally it would
be a frozen object at this point.

Spread Attributes
Now you can use a new feature of JSX called spread attributes:

var props = {};
    props.foo = x;
    props.bar = y;
    var component = <Component {...props} />;

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. Later attributes override
previous ones.

var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'

What’s with the weird … notation?
The … operator (or spread operator) is already supported for arrays in ES6. There is also
an ECMAScript proposal for Object Rest and Spread Properties. We’re
taking advantage of these supported and developing standards in order
to provide a cleaner syntax in JSX.