[javascript] 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}>

This question is related to javascript reactjs

The answer is


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


Three dots ... represents Spread Operators or Rest Parameters,

It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.

  • Merge two arrays

_x000D_
_x000D_
var arr1 = [1,2,3];_x000D_
var arr2 = [4,5,6];_x000D_
_x000D_
arr1 = [...arr1, ...arr2];_x000D_
console.log(arr1);  //[1, 2, 3, 4, 5, 6]
_x000D_
_x000D_
_x000D_

  • Copying array:

_x000D_
_x000D_
var arr = [1, 2, 3];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
console.log(arr); //[1, 2, 3]
_x000D_
_x000D_
_x000D_

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

  • Add values of one array to other at specific index e.g 3:

_x000D_
_x000D_
var arr1 = [4,5]_x000D_
var arr2 = [1,2,3,...arr1,6]_x000D_
console.log(arr2); // [1, 2, 3, 4, 5, 6]
_x000D_
_x000D_
_x000D_

  • When calling a constructor with new:

_x000D_
_x000D_
var dateFields = [1970, 0, 1];  // 1 Jan 1970_x000D_
var d = new Date(...dateFields);_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

  • Spread in object literals:

_x000D_
_x000D_
var obj1 = { foo: 'bar', x: 42 };_x000D_
var obj2 = { foo: 'baz', y: 13 };_x000D_
_x000D_
var clonedObj = { ...obj1 };_x000D_
console.log(clonedObj); //{foo: "bar", x: 42}_x000D_
_x000D_
var mergedObj = { ...obj1, ...obj2 };_x000D_
console.log(mergedObj); //{foo: "baz", x: 42, y: 13}
_x000D_
_x000D_
_x000D_

Note that foo property of obj1 has been overwritten by obj2 foo property

  • As a rest parameter syntax which allows us to represent an indefinite number of arguments as an array:

_x000D_
_x000D_
function sum(...theArgs) {_x000D_
  return theArgs.reduce((previous, current) => {_x000D_
    return previous + current;_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log(sum(1, 2, 3)); //6_x000D_
console.log(sum(1, 2, 3, 4)); //10
_x000D_
_x000D_
_x000D_

Note:Spread syntax (other than in the case of spread properties) can be applied only to iterable objects: So following will throw error

_x000D_
_x000D_
var obj = {'key1': 'value1'};_x000D_
var array = [...obj]; // TypeError: obj is not iterable
_x000D_
_x000D_
_x000D_

Reference1

Reference2


This a spread operator...

For example if you have an array first=[1,2,3,4,5] and another second=[6,7,8].

[...first, ...second] //result is [1,2,3,4,5,6,7,8]

The same can also be done with json objects.


In a short, the three dots ... is a spread operator in ES6(ES2015). Spread operator will fetch all the data.

let a = [1, 2, 3, 4];
let b = [...a, 4, 5, 6];
let c = [7,8,...a];


console.log(b);

Will give the result [1,2,3,4,5,6]

console.log(c);

Will give the result [7,8,1,2,3,4]


The ...(spread operator) is used in react to:

provide a neat way to pass props from parent to child components. e.g given these props in a parent component,

this.props = {
  username: "danM",
  email: "[email protected]"
}

they could be passed in the following manner to the child,

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

which is similar to this

<ChildComponent username={this.props.username} email={this.props.email} />

but way cleaner.


Its called spread operator. For eg let hello={name: '',msg:''} let hello1={...hello} Now hello object properties is copied to hello1.


... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed. This is not specific to React. It is a Javascript operator.

All these answers here are helpful, but I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator).

1. Combine Arrays (Concatenate Arrays)

There are a variety of ways to combine arrays, but the spread operator allows you to place this at any place in an array. If you'd like to combine two arrays and place elements at any point within the array, you can do as follows:

var arr1 = ['two', 'three'];
var arr2 = ['one', ...arr1, 'four', 'five'];

// arr2 = ["one", "two", "three", "four", "five"]

2. Copying Arrays

When we wanted a copy of an array, we used to have the Array.prototypr.slice() method. But, you can do the same with the spread operator.

var arr = [1,2,3];
var arr2 = [...arr];
// arr2 = [1,2,3]

3. Calling Functions without Apply

In ES5, to pass an array of two numbers to the doStuff() function, you often use the Function.prototype.apply() method as follows:

function doStuff (x, y, z) { }
var args = [0, 1, 2];

// Call the function, passing args
doStuff.apply(null, args);

However, by using the spread operator, you can pass an array into the function.

doStuff(...args);

4. Destructuring Arrays

You can use destructuring and the rest operator together to extract the information into variables as you'd like them:

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }

5. Function Arguments as Rest Parameters

ES6 also has the three dots ( ...) which is a rest parameter that collects all remaining arguments of a function into an array.

function f(a, b, ...args) {
  console.log(args);
}

f(1,2,3,4,5);
// [ 3, 4, 5 ]

6. Using Math Functions

Any function where spread is used as the argument can be used by functions that can accept any number of arguments.

let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1

7. Combining Two Objects

You can use the spread operator to combine two objects. This is an easy and cleaner way to do it.

var carType = {
  model: 'Toyota',
  yom: '1995'
};

var carFuel = 'Petrol';

var carData = {
  ...carType,
  carFuel
}

console.log(carData); 
// {
//  model: 'Toyota',
//  yom: '1995',
//  carFuel = 'Petrol'
// }

8. Separate a String into Separate Characters

You can use the spread operator to spread a string into separate characters.

let chars = ['A', ...'BC', 'D'];
console.log(chars); // ["A", "B", "C", "D"]

You can think of more ways to use the Spread Operator. What I have listed here are the popular use cases of it.


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

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

  1. Function arguments as array

     function fun1(...params) { 
    
     }  
    

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]

Kudos to Brandon Morelli. He explained perfectly here, but links may die so I am just pasting the content below:

The spread syntax is simply three dots: ... It allows an iterable to expand in places where 0+ arguments are expected. Definitions are tough without context. Let's explore some different use cases to help understand what this means.

Example #1 — Inserting Arrays Take a look at the code below. In this code, we don’t use the spread syntax:

_x000D_
_x000D_
var mid = [3, 4];_x000D_
var arr = [1, 2, mid, 5, 6];_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Above, we’ve created an array named mid. We then create a second array which contains our mid array. Finally, we log out the result. What do you expect arr to print? Click run above to see what happens. Here is the output:

[1, 2, [3, 4], 5, 6]

Is that the result you expected? By inserting the mid array into the arr array, we’ve ended up with an array within an array. That’s fine if that was the goal. But what if you want only a single array with the values of 1 through 6? To accomplish this, we can use the spread syntax! Remember, the spread syntax allows the elements of our array to expand. Lets look at the code below. Everything is the same — except we’re now using the spread syntax to insert the mid array into the arr array:

_x000D_
_x000D_
var mid = [3, 4];_x000D_
var arr = [1, 2, ...mid, 5, 6];_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

And when you hit the run button, here’s the result:

[1, 2, 3, 4, 5, 6]

Awesome! Remember the spread syntax definition you just read above? Here’s where it comes into play. As you can see, when we create the arr array and use the spread operator on the mid array, instead of just being inserted, the mid array expands. This expansion means that each and every element in the mid array is inserted into the arr array. Instead of nested arrays, the result is a single array of numbers ranging from 1 to 6.

Example #2 — Math JavaScript has a built in math object that allows us to do some fun math calculations. In this example we’ll be looking at Math.max(). If you’re unfamiliar, Math.max() returns the largest of zero or more numbers. Here are a few examples:

Math.max();
// -Infinity
Math.max(1, 2, 3);
// 3
Math.max(100, 3, 4);
// 100

As you can see, if you want to find the maximum value of multiple numbers, Math.max() requires multiple parameters. You unfortunately can’t simply use a single array as input. Before the spread syntax, the easiest way to use Math.max() on an array is to use .apply()

_x000D_
_x000D_
var arr = [2, 4, 8, 6, 0];_x000D_
_x000D_
function max(arr) {_x000D_
  return Math.max.apply(null, arr);_x000D_
}_x000D_
_x000D_
console.log(max(arr));
_x000D_
_x000D_
_x000D_

It works, it’s just really annoying. Now take a look at how we do the same exact thing with the spread syntax:

_x000D_
_x000D_
var arr = [2, 4, 8, 6, 0];_x000D_
var max = Math.max(...arr);_x000D_
_x000D_
console.log(max);
_x000D_
_x000D_
_x000D_

Instead of having to create a function and utilize the apply method to return the result of Math.max() , we only need two lines of code! The spread syntax expands our array elements and inputs each element in our array individually into the Math.max() method!

Example #3 — Copy an Array In JavaScript, you can’t just copy an array by setting a new variable equal to already existing array. Consider the following code example:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = arr;_x000D_
_x000D_
console.log(arr2);
_x000D_
_x000D_
_x000D_

When you press run, you’ll get the following output:

['a', 'b', 'c']

Now, at first glance, it looks like it worked — it looks like we’ve copied the values of arr into arr2. But that’s not what has happened. You see, when working with objects in javascript (arrays are a type of object) we assign by reference, not by value. This means that arr2 has been assigned to the same reference as arr. In other words, anything we do to arr2 will also affect the original arr array (and vice versa). Take a look below:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = arr;_x000D_
_x000D_
arr2.push('d');_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Above, we’ve pushed a new element d into arr2. Yet, when we log out the value of arr, you’ll see that the d value was also added to that array:

['a', 'b', 'c', 'd']

No need to fear though! We can use the spread operator! Consider the code below. It’s almost the same as above. Instead though, we’ve used the spread operator within a pair of square brackets:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
console.log(arr2);
_x000D_
_x000D_
_x000D_

Hit run, and you’ll see the expected output:

['a', 'b', 'c']

Above, the array values in arr expanded to become individual elements which were then assigned to arr2. We can now change the arr2 array as much as we’d like with no consequences on the original arr array:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
arr2.push('d');_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Again, the reason this works is because the value of arr is expanded to fill the brackets of our arr2 array definition. Thus, we are setting arr2 to equal the individual values of arr instead of the reference to arr like we did in the first example.

Bonus Example — String to Array As a fun final example, you can use the spread syntax to convert a string into an array. Simply use the spread syntax within a pair of square brackets:

_x000D_
_x000D_
var str = "hello";_x000D_
var chars = [...str];_x000D_
_x000D_
console.log(chars);
_x000D_
_x000D_
_x000D_


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.


These three dots are called spread operator. Spread operator helps us to create a copy state or props in react.

Using spread operator in react state

const [myState, setMyState] = useState({
    variable1: 'test',
    variable2: '',
    variable3: ''
});

setMyState({...myState, variable2: 'new value here'});

in the above code spread operator will maintain a copy of current state and we will also add new value at same time, if we don't do this then state will have only value of variable2 spread operator helps us to write optimize code


Spread Attributes used to Pass 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)


Is usually called spread operator, it is use to expand wherever is required

example

const SomeStyle = {
   margin:10,
   background:#somehexa
}

you can use this where ever you requires it more about spread operator Spread syntax.


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.


The meaning of ... depends on where you use it in the code,

  1. Used for spreading/copying the array/object - It helps to copy array/object and also add new array values/add new properties to object, which is optional.

_x000D_
_x000D_
const numbers = [1,2,3];_x000D_
const newNumbers = [...numbers, 4];_x000D_
console.log(newNumbers) //prints [1,2,3,4] 
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
const person = {_x000D_
 name: 'Max'_x000D_
};_x000D_
_x000D_
const newPerson = {...person, age:28};_x000D_
console.log(newPerson); //prints {name:'Max', age:28}
_x000D_
_x000D_
_x000D_

  1. Used for merging the function arguments into a single array - You can then use array functions on it.

_x000D_
_x000D_
const filter = (...args) => {_x000D_
   return args.filter(el => el ===1);_x000D_
}_x000D_
_x000D_
console.log(filter(1,2,3)); //prints [1] 
_x000D_
_x000D_
_x000D_


if you have an array of elements and you want to display the elements you just use ...arrayemaments and it will iterate over all the elements


It is called spreads syntax in javascript.

It use for destructuring an array or object in javascript.

example:

const objA = { a: 1, b: 2, c: 3 }
const objB = { ...objA, d: 1 }
/* result of objB will be { a: 1, b: 2, c: 3, d: 1 } */
console.log(objB)

const objC = { ....objA, a: 3 }
/* result of objC will be { a: 3, b: 2, c: 3, d: 1 } */
console.log(objC)

You can do it same result with Object.assign() function in javascript.

Reference:Spread syntax


The spread operator is three dots (...) that perform several different tasks. First, the spread operator allows us to combine the contents of arrays.

var peaks = ["Tallac", "Ralston", "Rose"]
var canyons = ["Ward", "Blackwood"]
var tahoe = [...peaks, ...canyons]
console.log(tahoe.join(', ')) // Tallac, Ralston, Rose, Ward, Blackwood

The spread operator can also be used to get some, or the rest, of the items in the array:

var lakes = ["Donner", "Marlette", "Fallen Leaf", "Cascade"]
var [first, ...rest] = lakes
console.log(rest.join(", ")) // "Marlette, Fallen Leaf, Cascade"

We can also use the spread operator to collect function arguments as an array.

function directions(...args) {
    var [start, ...remaining] = args
    var [finish, ...stops] = remaining.reverse()
    console.log(start, finish)
}

The spread operator can also be used for objects.

var morning = {
    breakfast: "oatmeal",
    lunch: "peanut butter and jelly"
}
var dinner = "mac and cheese"
var backpackingMeals = {
    ...morning,
    dinner
}
console.log(backpackingMeals) // {breakfast: "oatmeal", lunch: "peanut butter and jelly", dinner: "mac and cheese"}

Ref: Learning React: Functional Web Development with React and Redux by Alex Banks, Eve Porcello


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

spread operator(triple operator) introduce in ecama script 6(ES6).Ecama script(ES6) is a wrapper of javascript.

spread operator enumerable properties in props. this.props = { firstName: 'Dan', lastName: 'Abramov', city: 'New York', country: 'USA' }

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

But the main feature spread operator is used for a reference type.

For example
let person= {
    name: 'Alex',
    age: 35 
}
person1= person;

person1.name = "Raheel";

console.log( person.name); // output: Raheel

This is called reference type, one object affects other objects because they are shareable in memory. If you getting value independently mean spread memory both use spread operator.

 let person= {
        name: 'Alex',
        age: 35 
    }
person2 = {...person};

person2.name = "Shahzad";

console.log(person.name); // output: Alex

This will be compiled into:

React.createElement(Modal, { ...this.props, title: "Modal heading", animation: false }, child0, child1, child2, ...)

where it gives more two properties title & animation beyond the props the host element has.

... is the ES6 operator called Spread.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


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.


... this syntax is part of ES6 and not something which you can use only in React.It can be used in two different ways; as a spread operator OR as a rest parameter.You can find more from this article: https://www.techiediaries.com/react-spread-operator-props-setstate/

what you have mentioned in the question is something like this, let's assume like this,

    function HelloUser() {
      return <Hello Name="ABC" City="XYZ" />;
    }

with the use of spread operator you can pass props to the component like this.

     function HelloUser() {
       const props = {Name: 'ABC', City: 'XYZ'};
       return <Hello {...props} />;
     }

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.


const Profile =  {
          firstName: "kazi",
          lastName: "ahsan"
   }

const ProfileUpdate =  {
          firstName: "kazi",
          lastName: "ahsan"
 }


const newProfile = {...Profile, ...ProfileUpdate}

Hope this helps someone.


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 a maximum of 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

For someone who wants to understand this simple and fast:

First of all, this is not a syntax only to react. this is a syntax from ES6 called Spread syntax which iterate(merge, add..etc) array and object. read more about here

So answer to the question: let's imagine you have this tag:

<UserTag name="Supun" age="66" gender="male" />

and You do this:

const user = {
  "name"=>"Joe",
  "age"=>"50"      
  "test"=>"test-val"
};

<UserTag name="Supun" gender="male"  {...user} age="66" />

then the tag will equal this:

<UserTag name="Joe" gender="male" test="test-val" age="66" />

So what happened was when you use Spread syntax in a react tag it takes tag's attribute as object attributes which merge(replace if it exists) with the given object user. also, you might have noticed one thing that it only replaces before attribute, not after attributes. so in this example age remains as it is.

Hopes this helps :)


It is common practice to pass props around in a React application. In doing this we able to apply state changes to the child component regardless of whether it is Pure or Impure (stateless or stateful). There are times when the best approach, when passing in props, is to pass in singular properties or an entire object of properties. With the support for arrays in ES6 we were given the "..." notation and with this we are now able to achieve passing an entire object to a child.

The typical process of passing props to a child is noted with this syntax:

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

This is fine to use when the number of props is minimal but becomes unmanageable when the prop numbers get too much higher. A problem with this method occurs when you do not know the properties needed within a child component and the typical JavaScript method is to simple set those properties and bind to the object later. This causes issues with propType checking and cryptic stack trace errors that are not helpful and cause delays in debugging. The following is an example of this practice, and what not to do:

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

This same result can be achieved but with more appropriate success by doing this:

var props = {};
props.foo = x;
props.bar = y;
var component = Component(props); // Where did my JSX go?

But does not use JSX spread or JSX so to loop this back into the equation we can now do something like this:

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

The properties included in "...props" are foo: x, bar: y. This can be combined with other attributes to override the properties of "...props" using this syntax:

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

In addition we can copy other property objects onto each other or combine them in this manner:

var oldObj = { foo: 'hello', bar: 'world' };
var newObj = { ...oldObj, foo: 'hi' };
console.log(newObj.foo); // 'hi';
console.log(newObj.bar); // 'world';

Or merge two different objects like this (this is not yet available in all react versions):

var ab = { ...a, ...b }; // merge(a, b)

Another way of explaining this, according to Facebook's react/docs site is:

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. The following two examples 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. This syntax should be used sparingly.