What does …rest mean in ReactJS.
Here’s an example. Let’s assume we have an object tempObj
defined as follows:
const tempObj = {
name: 'Mahesh Joshi',
age: 30,
sex: 'M',
dob: new Date(1990, 1, 1)
};
For this example, it may help to just think of props
as having the same structure (i.e., properties and values) as shown in tempObj
. Now, let's write the following assignment.
const { name: Username, ...rest } = tempObj
The statement above amounts to both the declaration and assignment of two variables (or, I guess, constants). The statement can be thought out as:
Take property
name
defined ontempObj
and assign its value to a new variable we callUsername
. Then, take whatever other properties were defined ontempObj
(i.e.,age
,sex
anddob
) and collect them into a new object assigned to the variable we namerest
.
Logging Username
and rest
to the console
would confirm this. We have the following:
console.log(Username);
// => Mahesh Joshiconsole.log(rest);
// => { age: 30, sex: 'M', dob: Mon Jan 01 1990 00:00:00 GMT-0800 (PST) }