Skip to content Skip to sidebar Skip to footer

React Use .push To Add To An Array With Onclick

I am attempting to add to my existing array which is called players (which is an external file 'players.js' that's imported into my parent). I can write: players.push({ name: '

Solution 1:

Players is a property on the state object, so you'll want to call setState to update the property:

handleAddPlayer = () => {
  // create a clone of your array of players; don't modify objects on the state directly
  const players = this.state.players.slice(0);

  players.push({
    name: 'Maul',
    id: 26
  });

  this.setState({
    players: players,
  });
};

Post a Comment for "React Use .push To Add To An Array With Onclick"