Home » Reactjs » What do these three dots in React do?

What do these three dots in React do?

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

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

Those are JSX spread attributes:

Spread Attributes

If you already have props as an object, and you want to pass it in JSX, you can use ... as a “spread” operator to pass the whole props object. These two components are equivalent:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don’t care about them. We recommend that you use this syntax sparingly.

That documentation used to mention that although this is (for now) a JSX thing, there’s a proposal to add Object Rest and Spread Properties to JavaScript itself. (JavaScript has had rest and spread for arrays since ES2015, but not for object properties.) As of November 2017, that proposal is at Stage 3 and has been for some time. Both Chrome’s V8 and Firefox’s SpiderMonkey now support it, so presumably if the specification language is worked out in time it’ll be Stage 4 soon and part of the ES2018 snapshot specification. (More about stages here.) Transpilers have supported it for some time (even separately from JSX).


Side note: Although the JSX quote above talks about a “spread operator,” ... isn’t an operator, and can’t be. Operators have a single result value. ... is primary syntax (kind of like the () used with for aren’t the grouping operator, even though they look like it).

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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:

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

Questions:
Answers:

For those who come from the Python world, JSX Spread Attributes are equivalent to
Unpacking Argument Lists (the Python **-operator).

I’m aware this is a JSX question, but working with analogies sometimes helps to get it faster.

Questions:
Answers:

It’s just defining props in a different way in JSX!

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 {...person} 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.

Questions:
Answers:

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 JSX

Spread properties in object initializers copies own enumerable
properties from a provided object onto the newly created object.

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

Reference:

1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties

2) https://facebook.github.io/react/docs/jsx-spread.html

Questions:
Answers:

Passing the multiple Properties in a Simple Way

{ … this.props } is Holding the property of this.props

Use of the { … } Spread Operator with below props

this.props = 
 { 
    firstName: 'Dan', 
    lastName: 'Abramov', 
    city: 'New York',
    country: 'USA' 
}

Without { … } Spread

<Child 
  firstName={this.props.firstName}
  lastName={this.props.lastName}
  city={this.props.city}
  country={this.props.country}

> 

With { … } Spread

<Child { ...this.props } />

Dan Abramov’s Tweet about Spread operator (Creator of Redux) https://twitter.com/dan_abramov/status/694519379191545856?lang=en

Questions:
Answers:

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:

let array = [1,2,3]
let array2 = [...array]
// array2 is now filled with the items from array

And with an object/keys:

// lets pass an object as props to a react component
let myParameters = {myKey: 5, myOtherKey: 7}
let component = <MyComponent {...myParameters}/>
// this is equal to <MyComponent myKey=5 myOtherKey=7 />

What’s really cool is you can use it to mean “the rest of the values”.

const myFunc = (value1, value2, ...values) {
    // Some code
}

myFunc(1, 2, 3, 4, 5)
// when myFunc is called, the rest of the variables are placed into the "values" array

Questions:
Answers:

In your specific example, the spread operator will pass everything inside the props object.

I found this website to be really helpful when starting out with react : https://zhenyong.github.io/react/docs/jsx-spread.html

Questions:
Answers:

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 :

let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]

Leave a Reply

Your email address will not be published. Required fields are marked *