Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What do these three dots in React do?

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

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

2 Answers

kshitijrana14
... are called spread attributes which, as 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 going to 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.
aashaykumar
228

The three dots represent the spread operator in ES6. It allows us to do quite a few things in JavaScript:

Concatenate arrays

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']

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']

Combining 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'}

There's another use for the three dots which is known as Rest Parameters and it makes it possible to take all of the arguments to a function in as one array.

Function arguments as array

function fun1(...params) {

}

Login / Signup to Answer the Question.