React 'cannot read property of undefined' when using map
Solution 1:
You have not done binding for the map function where you are using onScoreChange = {this.onPlayerScoreChange}
,
you can either use bind or arrow functions for binding
P.S. Binding is needed because the context of the map function is different from the React Component context and hence this
inside this function won't be Referring to the React Components this
and thus you can't access that properties of the React Component class.
With Arrow function:
{this.state.initialPlayers.map((player, index)=> {
return(
<Player
name = {player.name}
score = {player.score}
key = {player.id}
index = {index}
onScoreChange = {this.onPlayerScoreChange}
/>
)
})}
With bind
{this.state.initialPlayers.map(function(player, index) {
return(
<Player
name = {player.name}
score = {player.score}
key = {player.id}
index = {index}
onScoreChange = {this.onPlayerScoreChange}
/>
)
}.bind(this))}
Solution 2:
Can also be done by passing second argument as this to map function as onClick event uses local this of map function which is undefined here and this currently refers to the global object.
{this.state.initialPlayers.map(function(player, index) {
return(
<Player
name = {player.name}
score = {player.score}
key = {player.id}
index = {index}
onScoreChange = {this.onPlayerScoreChange}
/>
)
}),this}