Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript One Solution

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Would anyone be able to further explain the use of the spread operator in this case?

I understand what the spread operator does, and (I think) I even understand what it's doing here, but I can't seem to find the documentation to really explain it.

How is this...:

const PlanetList = (props) => {
  return (
    <div className="container">
      {props.planets.map((planet) => (
        <Planet {...planet} key={planet.id} />
      ))}
    </div>
  );
};

...the same as this:

const PlanetList = (props) => {
  return (
    <div className="container">
      {props.planets.map((planet) => (
        <Planet
          key={planet.id}
          url={planet.url}
          name={planet.name}
          desc={planet.desc}
          diameter={planet.diameter}
          moons={planet.moons}
        />
      ))}
    </div>
  );
};

Am I correct in assuming that the spread operator (in this case) spreads the current object and creates new component properties that use the current object property as the name, and sets the value to the corresponding property of the current object being mapped over? Does this also mean the spread operator will only work if the properties of the object and the properties of the component has the exact same name?

Thanks in advance! I've just never used the spread operator this way before.

Hi Joseph Michelini,

You may have never used the spread operator that way before, but you seem to have a good understanding of how it works. You are absolutely right in your analysis of whatโ€™s going on in the first code example.

Here are two articles you might find interesting:

This first one Iโ€™ve chosen because it covers both the spread operator and destructuring (specifically with respect to React): https://www.carlrippon.com/writing-concise-react-components-with-destructure-assignment-and-spread/

This second one is the topic of the spread syntax as covered by MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Happy coding!

1 Answer

hi Joseph , yes you are totally right it will only work if the properties of the object and the properties of the component has the exact same name thanks to the new ES6 syntax