Open In App

What is the Meaning of Spread Operator (...) in Reactjs?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Spread Operator ( ... ) in react is used to manage and manipulate props, arrays, and states. It is a JavaScript ES6 feature that allows to expand the arrays, objects, and any other iterable items.

What is Spread Operator

The Spread Operator is a JavaScript feature introduced in ES6 which is used to expand the iterable items. The three dots syntax (...) is used by two operators i.e. the Spread Operator and Rest Parameter. The Spread operator lets you expand an iterable like an object, string, or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array.

Syntax:

// For array expansion
const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5]; // [1, 2, 3, 4, 5]

// Object Expansion
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// Passing Props
const childProps = { name: 'John', age: 25 };
<ChildComponent {...childProps} />

// Managing State
this.setState((prevState) => ({
  ...prevState,
  user: { ...prevState.user, name: "New Name" }
}));

The spread operator is very useful when you want to make an exact copy of an existing array, you can use the spread operator to accomplish this quickly.

Steps to Create React Application

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure:

project-structure---spread-operator-in-react



Example: This example uses the spread operator to pass the person object's properties (name and age) as individual props to the Details component.

JavaScript
// Filename - App.js

import React, { Component } from "react";

// Details is a component in same folder
import Details from "./Details";
class App extends React.Component {
	render() {
		var person = {
			name: "User",
			age: 22
		};

		return (
			<div>
				{/* Details component which accepts props */}
				<Details {...person} title="Dear" />
			</div>
		);
	}
}

export default App;
JavaScript
// Filename - Details.js

import React, { Component } from "react";

class Details extends React.Component {
	render() {
		// To extract values in variables sent by parent component
		const { name, age } = { ...this.props };
		return (
			<div>
				<h3>Person Details: </h3>
				<ul>
					<li>
						name={this.props.title} {name}
					</li>
					<li>age={age}</li>
				</ul>
			</div>
		);
	}
}

export default Details;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Next Article

Similar Reads