What three dots mean in React code?

Experience Level: Junior
Tags: React

Answer

In React code, three dots (…) are used to spread an object or an array. This is called the spread operator and it allows us to expand an iterable object into individual elements. The spread operator can be used in various scenarios such as passing props to a component, merging objects, and copying arrays.

One common use case for the spread operator is when passing props to a component. Instead of passing each prop individually, we can use the spread operator to pass all the props at once. This makes the code more concise and easier to read. For example:


const props = {
  name: 'John',
  age: 30,
  city: 'New York'
};

return (
  <MyComponent {...props} />
);

In the above example, we are passing the props object to the MyComponent component using the spread operator. This is equivalent to passing each prop individually like this:


return (
  <MyComponent 
    name={props.name} 
    age={props.age} 
    city={props.city} 
  />
);

Another use case for the spread operator is when merging objects. We can use the spread operator to create a new object that contains the properties of two or more objects. For example:


const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };

console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }

In the above example, we are merging obj1 and obj2 into a new object called mergedObj using the spread operator. This creates a new object that contains all the properties of obj1 and obj2.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself