DEV Community

Ray
Ray

Posted on

React: Rest and Spread Operator

Kia Ora!
Did you guys all try it yourself with the homemade VPN instruction I brought last week?
This week I continue my React learning notes and today I bring you the application of Rest and Spread Operator features in React.

Rest Operator
Continuing on from last week we discussed the code section on Destructuring Objects.
Image description

We deposited primaryGenre, and secondaryGenre into Array: genres. Now we want to extract the other genres as well. This is where we can use 'the rest operator'
Image description
After secondaryGenre we add '...(any name)', which will automatically add all the values to this Array, even if we didn't define them separately like we did for the first and second one.

**Note! **Here we can notice that all the remaining values are deposited into the same Array, except for the first and second Genre already defined, so '.... . otherGenres' can only be placed in the last bit of the const definition, and if the rest operator is placed in the middle of the first and second one, it will report an error.
Image description

Spread Operator
Now let's switch to a different scenario: create a new Array with all the genres, while adding a new genre at the end. If we add it like this, we can see that our new genre is not in the same Array as
Image description all the other genres.

At this point, we use '...' again. Add our new genre. like the one shown below, and this time the result is what we want.
Tips: If you want to add to the top of the Array, put '...genres' after it.
Image description

Spread Operator can be used not only in Array but also in objects is very important, it can help us to add new properties and also help to update the old properties.
Creates an updatedbook object, calls an existing book object and adds a 'moviePublicationDate'.
You can see this new property at the end.
Image description

Creates an updatedbook object, calls an existing book object and adds a 'moviePublicationDate'.
You can see that this new property is not where we want it to be, it's outside of this book object.
Image description

We can add the moviePublicationDate to the book object by using the Spread Operator in the same way as we did with the Array.
Image description
You can see that at this point the page value of books is 1216, now let's try to update this data. At the end of the updatedbook object, add the change to the page property, and you can see that we have successfully updated the value from 1216 to 1220.

Image description
Note: As the Rest and Spread Operator I mentioned earlier when we put the Rest & Spread Operator in front of the book, we can copy the original data first, and then we can overwrite the updated data later, but if we put the Rest & Spread Operator in the back of the book, we can't! successfully overwrite.

Image description

Top comments (0)