0

I have an array that I'd like to add a new name from the user's input. In my component I have:

<div>
  <h4>Add A Player</h4>
  <input
    type="text"
    placeholder="Enter a new name"
    value={this.state.newPlayerName}
  />
  <button onClick={this.handleAddPlayer}>
     Press to Add Player
  </button>
</div>

Which works with this function except for the name:

handleAddPlayer = e => {
  const players = this.state.players.slice(0);
  players.push({
    name: '',
    id: getRandomInt(20, 55)
  });
  this.setState({
    players: players,
    newPlayerName: e.target.value
  });
};

I'm trying to get when a user inputs a name and submits it, it updates in the function which updates the array (if this makes sense, apologies as this is still pretty new to me).

In my state I have:

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

I'm not sure how to get the input to pass the name (or string) to the array, can anyone help?

0

1 Answer 1

1

First of all, you added bound input-updating handler to the wrong element! You currently have it attached to a button, you have to have it attached to the input! Add an onChange handler to your input to update the value every time you change the input:

<input
  type="text"
  placeholder="Enter a new name"
  value={this.state.newPlayerName}
  onChange={this.handleChange}
/>

Then create a new method that handles the change:

handleChange = e => {
  this.setState({
    newPlayerName: e.target.value
  });
}

This will let React control the input, and set the input value in state so you can use it when adding a new player. Then, set up the handler to add a new player on click. Instead of slicing, pushing, the resetting, just use array spread syntax:

handleAddPlayer = e => {
  this.setState(prevState => ({
    players: [...prevState.players, {
      name: this.state.newPlayerName
      id: getRandomInt(20, 55)
    }]
  }));
}

This will set players to the previous state's players property plus the new player object with a name that's the input's value and a random id.

Sign up to request clarification or add additional context in comments.

Comments

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.