React JS ES6: spread operator
ReactJS spread operator
1 Overview
📘 spread operator
The JavaScript spread operator
...
allows us to quickly copy all or part of an existing array or object into another array or object.
The spread operator is a useful tool for working with arrays and can make your code more concise and easier to read.
App.js
The spread operator is often used in combination with destructuring.
The spread operator can also be used to spread the elements of an array into the arguments of a function:
2 Copying objects with the spread syntax
We need to use spread operator to quickly copy part of the existing Person object (state variable
) into another new object (state variable
).
Note that the … spread syntax is “shallow”—it only copies things one level deep. This makes it fast, but it also means that if you want to update a nested property, you’ll have to use it more than once.
App.js
import { useState } from 'react';
export default function Form() {
const [person, setPerson] = useState({
firstName: 'Barbara',
lastName: 'Hepworth',
email: 'bhepworth@sculpture.com'
});
function handleChange(e) {
setPerson({
...person,
[e.target.name]: e.target.value
});
}
return (
<>
<label>
First name:
<input
name="firstName"
value={person.firstName}
onChange={handleChange}
/>
</label>
<label>
Last name:
<input
name="lastName"
value={person.lastName}
onChange={handleChange}
/>
</label>
<label>
Email:
<input
name="email"
value={person.email}
onChange={handleChange}
/>
</label>
<p>
{person.firstName}{' '}
{person.lastName}{' '}
({person.email})
</p>
</>
);
}
Here, you want to also copy the existing data into the new object to be rendered next render (that is lastName
and email
) because only one of the fields has changed: firstName
from input
and e.target.value
to trigger setPerson
.
So with big objects we must use spread operator.
App.js
Use spread operator
to create a new object and pass it to setPerson
.
You can use the … object spread syntax so that you don’t need to copy every property separately.