2

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: 'Maul',
  id: 26
});

And that works as ID is used for the key and the name is updated in the array.

However if I write

   handleAddPlayer = () => {
    console.log('i am working');
    players.push({
      name: 'Maul',
      id: 26
    });
  };

And on my button I have

    <div>
      <h4>Add A Player</h4>
      <input />
      <button onClick={this.handleAddPlayer}>Press to Add Player</button>
    </div>

And my state is as follows:

  this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  players,
};

It does not work.

From here I have two questions:

  1. why won't it update when I click the button but works before not as a function?

  2. I would like to put a name into the input and generate a unique key that's added into my array, players.js

I've tried concatenate and had not a lot of success.

2
  • can you tell us the error you get? Isn't it "Cannot read property 'push' of undefined"? Commented Jul 9, 2017 at 2:56
  • I don't get an error at all it's that nothing happens Commented Jul 9, 2017 at 2:59

1 Answer 1

8

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,
  });
};
Sign up to request clarification or add additional context in comments.

3 Comments

ok that worked like a charm and I learned a lot too, so thank you! Would you perchance be able to help me understand how the <input> can pass the value into the name and id can be a unique number?
wait, I got the random #, figured that out. now just passing the value from <input> into the name: area
Take a look at facebook.github.io/react/docs/forms.html#controlled-components, one way to do it is to add a property on the state such as value that maintains the value of the text input, then update your input to <input type="text" value={this.state.value} onChange={this.handleChange} />. Then your handleAddPlayer method can simply look at this.state.value to extract the value in the input box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.