0

I have a class component that uses the map method to access an array of objects. I Then use an implicit return to turn each object into a component. From my understanding the map method can only take an array, then pass a function to change the array.I don't understand why my code below works?

class App extends Component {
  state = {
    players: [
      {
        name: "Guil",
        id: 1
      },
      {
        name: "Treasure",
        id: 2
      },
      {
        name: "Ashley",
        id: 3
      },
      {
        name: "James",
        id: 4
      }
    ]
  };
  
    render() {
    return (
      <div className="scoreboard">
        {this.state.players.map( player =>
          <Player
            name={player.name}
            id={player.id}
            key={player.id.toString()}
            removePlayer={this.handleRemovePlayer}
          />
        )}
      </div>
    );
  }
}
Paine8887
  • 33
  • 6
  • 1
    `map` function will return an `Array`, in your case an `Array` of `Player` component – boosted_duck Jan 02 '20 at 05:43
  • `map()`, `filter()` and `reduce()` take an array and return a *new* array. They don't change the existing array. Some methods do change the existing array, such as `.push()`, gotta make sure you check which methods mutate the array and which ones don't before you use. The "implicit return" is essentially saying "for each element in the array, return _this_ in its place in the new array" – Jayce444 Jan 02 '20 at 05:52
  • Maybe your misunderstanding comes from the lambda? Maybe a simple example of doubling numbers would help `[1,2,3].map(i => i * 2); // [2,4,6]` The lambda is a function and if the right hand side of `=>` is an expression then it returns the result of running that expression. Map will put the results of each call into a new array and that is the result. – justin.m.chase Jan 02 '20 at 05:53

2 Answers2

1

From MDN

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

The map() never change the original array but just create a new array according to the provided function.

In your code, the map() method creates a new array of Player components(the result of the provided callback).

Pengson
  • 845
  • 5
  • 10
-1

The way you used is the same as what you said:"take an array, then pass a function to change the array".Here is the arrow function and an implicit return action.

fengxh
  • 384
  • 2
  • 8