2

I simply want to change the state of my app with a handleChange method for multiple checkboxes.

My state is changed from false to true when I click each of my checkboxes, but when I un-check it, my state doesn't change to reflect it and I cant seem to figure out why!

import React, { Component } from "react";

export class StepOne extends Component {
    constructor(props) {
        super(props);
        this.state = {
            box1: false,
            box2: false,
            box3: false,
        };
    }

    handleChange = (evt) => {
        const box = evt.target.name;
        this.setState({ [box]: !this.state.box });
    };

    render() {
        return (
            <div>
                <input type="checkbox" name="box1" onChange={this.handleChange} />
                <input type="checkbox" name="box2" onChange={this.handleChange} />
                <input type="checkbox" name="box3" onChange={this.handleChange} />
            </div>
        );
    }
}

2 Answers 2

1

When using a dot notation, compiler tries to look for a field called box in the state and since it doesn't exist - you are not getting any result when toggling the checkbox.

Use a bracket notation instead:

handleChange = (evt) => {
    const box = evt.target.name;
    this.setState((prevState) => ({ 
       [box]: !prevState[box],
    }));
};

Note: Consider using a function when setting the state to be sure that you refer to the relevant state.

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

Comments

1

you just have to make a change in your handleChange function as below:

  handleChange = (evt) => {
    const box = evt.target.name;
    this.setState([box]: evt.target.checked);
  };

this will give the state the same checked state of the checkbox (if the checkbox is checked, the state will be set to true, if it is not, it will be set to false). If you have any other problem with this solution you can comment so i can help you more

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.