Home > database >  What does {... player} mean in react?
What does {... player} mean in react?

Time:08-07

I tried to make a list with react, and from random site I found

        players.map((player) => (
          <PlayerItem
            key={player.id}
            id={player.id}
            {...player} />
        ))

Also, I have the players list, but I don't know what the {... } means, maybe someone can explain the meanings?

CodePudding user response:

It means that you pass all the properties in the player object as props to the PlayerItem.

If player is like below:

let player = { name: "pqr", data: "abc"}

Then it's the same as the following:

<PlayerItem
    key={player.id}
    id={player.id}
    name={player.name} 
    data={player.data}
/>

It's a short-hand way that saves time as you don't need to care separately about each property.

See spread operator

CodePudding user response:

This is not a React specific feature, but JS in general, and called spread. Let's assume you have a player object that looks like:

{
   id: 1,
   name: "player"
   url: "https://...."
}

writing:

<PlayerItem {...player} />

is the equivalent of writing

<PlayerItem id={player.id} name={player.name} url={player.url} />

CodePudding user response:

{...player} - looks like javascript spread operator. In react is easy way to automatically apply all the props

here is mozilla documentation about spread operators

CodePudding user response:

Basically ... is called as the spread operator in javascript. It basically expands an iterable object (in your case the 'players' list)

function sum(x, y, z) {
  return x   y   z;
}

const numbers = [1, 2, 3];

// Function 1
console.log(sum(...numbers));
// expected output: 6


// Function 2
console.log(sum(numbers[0], numbers[1], numbers[2]));
// expected output: 6

in the above example, Function 1 is written using the spread syntax.

  • Related