React Spread Operator ( …)

The spread operator () in Reactjs is used to expand an iterable (e.g. an array) into individual elements. It is often used to pass props down to child components or to merge objects together. For example, if you have an array of items and you want to pass them as props to a child component, you can use the spread operator to expand the array into individual props. This is often useful when there are lots of props to pass to the child component. Below are some examples of doing this.

1. Passing props down to child components:


const parentComponent = () => {
  const items = ['apple', 'banana', 'orange'];
  return (
    <ChildComponent {...items} />
  );
}

const childComponent = ({ apple, banana, orange }) => {
  return (
    <div>
      <p>{apple}</p>
      <p>{banana}</p>
      <p>{orange}</p>
    </div>
  );
}

In this example, we have a parent component (parentComponent) and a child component (childComponent). The parent component has an array of items (items) that it wants to pass down to the child component as props.

To do this, the parent component uses the spread operator () to expand the items array into individual props and passes them to the child component:

(<ChildComponent {...items} />).

This is equivalent to passing the items as individual props like this:

<ChildComponent apple="apple" banana="banana" orange="orange" />.

Then in the child component, we destructure the props object to get each individual item as a prop:

(({ apple, banana, orange })).

We can then use these props to render each item in the component.

2. Merging objects together:


const obj1 = { name: 'John', age: 30 };
const obj2 = { occupation: 'Developer' };
const mergedObj = { ...obj1, ...obj2 };

console.log(mergedObj);
// Output: { name: 'John', age: 30, occupation: 'Developer' }

In this example, we have two objects (obj1 and obj2) that we want to merge together into a single object (mergedObj).

To do this, we use the spread operator () to spread the properties of each object into a new object. By doing this, we create a new object (mergedObj) that contains all the properties from obj1 and obj2.

In this case, the resulting object (mergedObj) has the properties name, age, and occupation. The values for these properties are taken from the original objects (obj1 and obj2).

Happy learning …