The spread operator in React

In the beginning of my journey to learn react, I thought the array in javascript had no more secret for me until …

Pushing an element

my .push wont work !!

Just using a .push() won’t return was your expecting, let’s see below:

If we want to add 6 with .push(), we won’t get our array back !!!

let array =[1, 2, 3]
(3) [1, 2, 3]
// simple array with Numbers

That’s when the spread operator […] makes it sense . The spread operator can be used to take an existing array and add another element to it while preserving the original array.

let array =[1, 2, 3]
//(3) [1, 2, 3]

In React

How in practice it looks like when we have our array as a state and we need to make an update :

addNumber(num) {
this.setState({
array: [...this.state.array, num]
})
}

When the addNumber() function is called and passed a number, the array key is updated so that it now includes the previous state in addition of the new number.

But You can still use .push()

addNumber(num) {

Yes a .push() still works but it adds extra steps when the spread operator is straight forward.

The spread operator is one of those tools I never really used before react. But when working with updating arrays, combining arrays etc … It makes your life easier.

Note about Objects.

The spread operator works the same way if it s an array of objects and can be also used to add a key, value pair to an object.

addObject(key,value) {

and also using to update a nested state without overwrite the data

{ 
name: 'john',

Software Engineering student @Flatiron