Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
like image 767
Edward Tanguay Avatar asked Aug 05 '26 13:08

Edward Tanguay


1 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}
/>
like image 193
Yousaf Avatar answered Aug 08 '26 03:08

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!