D
D
danilr2019-05-27 10:10:55
JavaScript
danilr, 2019-05-27 10:10:55

Why is the name wrapped in an array in the setState method?

Entries from the React documentation - why is name wrapped in an array in the setState method? Without a wrapper in an array does not work, why?

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
    console.log(name)
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <Reservation />,
  document.getElementById('root')
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2019-05-27
@danilr

in order to put the key in state not name but its value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question