{

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 allows expansion of the enumerable properties of an object, which means 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. To add those numbers to another array in between, spread operator placed and results into copying multiple properties to result.

It helps to pass at least zero arguments i.e. dynamic properties.

How do react components use three dots?

var employee= {
    name: 'Franc',
    id: 1,
    salary:5000
}

How this data transferred as props from parent to child 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.

Similarly, rewriting above 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 example

This spread operator is used in react hooks to update state objects.

React state object is initialized with default object properties using useState object useState object returns initial state and function which updates state.

While doing update the state, spread operator copy the original data with new values. It will only updates the properties which is not changed.

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

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 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 state will do 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, nested object is initialized in state object

state = {
    id:1,
    name:"John",
    dept:{
        name:"Sales"
    }
}

How do you update the nested json object in react state?

ie you want to update the name in dept. to new value i.e dept:{name:“Support”}

using three dots in state object, you can update easily

this.setState({ dept: {
  ...this.state.dept,
  name: 'support'
}})
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.