HPJM
HPJM

Reputation: 537

Toggling checkboxes in React

I'm having a frustrating problem trying to toggle checkboxes in React.

When I check the box, the state updates, and the state, previous state, and checked display true when I console.log them, which is weird in itself. But the checkbox doesn't check.

State

    this.state = {
        type: {
            prop1: false,
            prop2: false
        }
    }

Handling event change

handleCheckbox(e) {
    const name = e.target.name;
    const checked = e.target.checked;
    this.setState((prevState) => {
        this.state.type[name] = !prevState.type[name];
    });
}

Checkbox

<input
   type="checkbox"
   name="prop1"
   id="string"
   className="modal__checkbox-input"
   checked={this.state.type.prop1}
   onChange={this.handleCheckbox}
/>

Upvotes: 1

Views: 7121

Answers (2)

Birbal Singh
Birbal Singh

Reputation: 1072

update your handleCheckbox old state you will find as this.state

handleCheckbox(e) {
    const name = e.target.name;
    const checked = e.target.checked;
    const d = this.state.type;
    d[name] = !d[name];
    this.setState({ type : d });
}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281990

From your functional setState, you need to return the state to be updated and not mutate the original state

handleCheckbox(e) {
    const name = e.target.name;
    const checked = e.target.checked;
    this.setState((prevState) => {
        return {
           type: {
              ...prevState.type,
              [name]: !prevState.type[name]
           }
        }
    });
}

Upvotes: 2

Related Questions