Why is a spread operator required when using .map() in React, but not in plain JavaScript?

Viewed 1923

In a React application, I'm passing in this array of objects to a component:

const flashcards = [
    {
        "back": "bbb1",
        "front": "fff1",
        "id": 21
    },
    {
        "back": "bbb2",
        "front": "fff2",
        "id": 22
    },
    {
        "back": "bbb3",
        "front": "fff3",
        "id": 20
    }
];

In the component, when I map through the array, why do I need to have a spread operator in order to send individual items from the array to the next lower component (Flashcard), e.g. like this:

render() {
    return (
        <div className="app">
            <div>
                {this.props.flashcards.map(flashcard =>
                    <Flashcard {...flashcard} key={flashcard.id} />
                    )}
            </div>
        </div>
    );
}

This seems superfluous, since when I use map in plain JavaScript on the same array, I do not need the spread operator, e.g.:

flashcards.map(flashcard => console.log(flashcard.front));
3 Answers

{...flashcard} - This basically spreads the properties in flashcard object on the props object that Flashcard component will receive.

This is not necessary if you don't want to pass all the properties of flashcard object as props to Flashcard component.

Think of this

<Flashcard {...flashcard} key={flashcard.id} />

as a shorter way of writing this:

<Flashcard
   key={flashcard.id}
   back={flashcard.back}
   front={flashcard.front}
   id={flashcard.id}
/>

Because props were meant to flow in single direction, which is from parent to child. And when you have a prop which is a reference value such as array or object. Any write operation to it will change the value in reference memory which will modify the prop from child component. Hence destructing it creates a new memory reference and saves it from getting modified


Because it is syntactical sugar. Otherwise you had to write out the properties like in your example e.g.

 {this.props.flashcards.map(flashcard =>
      <Flashcard back={flashcard.back} front={flashcard.front} key={flashcard.id} />
  )}
Related