mardi 26 novembre 2019

React form checkbox state not changing correctly

I have a form with four checkboxes that I'm tracking the value. Initially, the state of the checkboxes is set to false, but when I 'check' the box for the first time, the state remains false, and then when I 'uncheck' it, it turns to true. From that point the checkbox state holds the opposite value of what it's supposed to be.

Component code:


class GuestForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      yoga: false,
      detox: false,
      massage: false,
      breath: false
    };

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


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

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

  render() {
    return (
      <form>
        <label>
          Activity Preferences:
          <label>
            <input 
              type='checkbox' 
              name='yoga'
              id='yoga'
              checked={this.state.yoga}
              onChange={this.onCheckboxChange} 
            />
            Yoga
          </label>
          <label>
            <input
              type='checkbox'
              name='detox'
              id='detox'
              checked={this.state.detox}
              onChange={this.onCheckboxChange}
            />
            Juice Detox
          </label>
          <label>
            <input
              type='checkbox'
              name='breath'
              id='breath'
              checked={this.state.breath}
              onChange={this.onCheckboxChange}
            />
            Breath-work
          </label>
          <label>
            <input
              type='checkbox'
              name='massage'
              id='massage'
              onChange={this.onCheckboxChange}
              value={this.state.massage}
            />
            Massage
          </label>
        </label>
        <input type='submit' value='Submit' />
      </form>
    );
  }
}

export default GuestForm;



Aucun commentaire:

Enregistrer un commentaire