Jereme
Jereme

Reputation: 525

Toggle boolean on state in react

I feel like I've done it correctly but the state is not being toggled. My state doesn't change to true when the checkbox is checked.

export default class Room extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
           isChecked: false
        };

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

 toggleChecked() {
        this.setState({ isChecked: !this.state.isChecked });
    }

 selectAllRooms(){
        if(this.state.isChecked === true){
           //do smth; 
        }else{
           //do smth;
    }

render() {
    return (
       <Modal.Footer>
            <Checkbox onChange={this.toggleChecked}> Select All Rooms </Checkbox>
       <Modal.Footer> 
  )
 }
)

Upvotes: 2

Views: 6212

Answers (1)

romedu
romedu

Reputation: 136

In react state updates may be asynchronous, if you wish to access the previous values you should do it in the following manner:

toggleChecked() {
    this.setState(prevState => ({ isChecked: !prevState.isChecked }));
}

When you pass in a function to the setState method the first argument makes reference to the previous state and the second the previous props.

Docs: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Upvotes: 3

Related Questions