React ‘cannot read property of undefined’ when using map

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))}

Leave a Comment