{

Three dots in react components with example|Spread operator


This is basic example for what is three dots(…) in reactjs and JSX. Three dots in react used to pass object properties from react hierarchy components, and also updating nested json object in react application.

three dots(…) also called spread attribute or spread syntax in javascript, It introduced as part of ES6. You can check my previous tutorial on [Spread operator](2018/08/es6-spread-operator-in-javascript.html)

What does three dots do?

It allows to expand the enumerable properties of an object , that means array expressions or string or object properties are enumerable properties

Let’s see simple example 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 other array in between, spread operator placed and results into copying multiple properties to result.

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

How react components uses 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 larger set of properties to pass an object to react component.

This looks not clean way of passing like this.

Similarly, rewriting above with spread operator syntax

<Employee {...employee}>

This is clean way of passing data from one component to another component.

three dots in react hooks example

This spread operator can also be used in react hooks to update state object.

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 an 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 can be used in changing react state properties Let’s declare state in constructor as follows.

    this.state = { name: "Fran" }

State can be updated using setState method with an object parameters.

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 new object with this. passing … to this.state will do shallow merge into new state.

Both approaches are helpful and do the same, but first syntax is difficult when you have a nested object in state tree.

For example, nested object is initialized in state object

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

How do you update nested json object in react state?

ie you want to update 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.