Three dots in react components with example|Spread operator
It is a simple example of three dots(...)
in reactjs and JSX.
Three dots (...)
in react specify to pass object properties from react components hierarchy. It also updates nested json objects in react application.
three dots(...)
is also called spread attribute
or spread syntax
in javascript.
It was introduced as part of ES6. You can check my previous tutorial on `Spread operator.
What does three dots do?
It has different behavior in different scenarios.
- used in Object and Array
It allows expansion of the enumerable properties of an object, array expressions or string or object properties are enumerable properties.
Let’s see a simple example of how it expands the enumerable properties.
var data = ["3", "4", "5"];
var numbers = ["1", ...data, "6", "7"]; // ["1", "3", "4", "5", "6","7"]
In the above example, data contains multiple enumerable properties as an array.
To add those numbers to another array in between, the spread operator copy all values and clones, copying multiple properties to the result.
It helps to pass at least zero arguments i.e. dynamic properties.
How do react components use three dots?
Let’s have an employee object in react component.
var employee = {
name: "Franc",
id: 1,
salary: 5000,
};
How this data transferred as props from parent to child component.
For example, You want to pass this data in react component to the Person component without the spread operator
<Person name="{employee.name}" id="{employee.id}" salary="{employee.salary}" />
This is received as props with name, id, and salary in the Person component
How about if there are a larger set of properties to pass an object to react component.
It looks not a clean way of passing like this.
Let’s see another way to rewrite the above code with spread operator syntax
.
<Employee {...employee}>
It is a clean way of passing data from one component to another component.
three dots in react hooks functional component example
This spread operator uses in react hooks to update state objects in clean manner.
React state object is initialized with default object properties using the useState
object The useState
object returns the initial state and function that updates the state.
While doing update the state, the spread operator copies the original data with new values. It will only update the properties which are not changed.
In the below example,
useState called with object default values and returned.
the employee is a state variable that holds default values
setEmployee
is a function that updates the state of a component, It contains the code to update the state with initial values and new values.initial values are passed as spread attributes.
const [employee, setEmployee] = useState({
id: "",
name: "",
salary: "",
});
setEmployees([
...employees,
{
name: "John",
id: "10",
salary: "5000",
},
]);
Here is a complete example:
import React, { useState } from "react";
function HookSpreadArray(props) {
const [employe, setEmploye] = useState([]);
const [name, setName] = useState("");
const saveEmploye = (event) => {
event.preventDefault();
setEmploye([
...employe,
{
name: name,
},
]);
setName("");
};
return (
<div>
<>
<form onSubmit={saveEmploye}>
<label>
Name
<input
name="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<button name="Save" value="Save">
Save
</button>
</form>
<ul>
{employe.map((emp) => (
<li key={emp.empid}>{emp.name}</li>
))}
</ul>
</>
</div>
);
}
export default HookSpreadArray;
spread operator in react state
The spread operator used in changing react state properties Let’s declare the state in the constructor as follows.
this.state = { name: "Fran" };
The state can be updated using the setState
method with an object parameter.
The first way, with simple syntax
this.setState({ name: "kiran" });
Second, The same can be achieved with the spread operator or three dots syntax
this.setState({ ...this.state, name: "kiran" })
)
As you see, merging the existing state with a new object with this. passing ...
to this, the old state does a shallow merge into a new state.
Both approaches are helpful and do the same, but the first syntax is difficult when you have a nested object in the state tree.
For example, the nested object is initialized in the state object.
state = {
id: 1,
name: "John",
dept: {
name: "Sales",
},
};
How do you update the nested json object in react state?
In Nested Object, you want to update the nested property i.e name in dept to a new value i.e dept:{name:"Support"}
using three dots in the state object, you can update easily
this.setState({
dept: {
...this.state.dept,
name: "support",
},
});
Summary
Learned Spread operator in React Functional and Class components with examples.
It is useful for clean code in react components.