close

How to toggle boolean state of react component?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to toggle boolean state of react component? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to toggle boolean state of react component ?

  1. How to toggle boolean state of react component ?

    to toggle boolean state of react component Set: const [state, setState] = useState(1);
    Toggle: setState(state*-1);
    Use: state > 0 ? 'on' : 'off';

  2. How to toggle boolean state of react component ?

    to toggle boolean state of react component Set: const [state, setState] = useState(1);
    Toggle: setState(state*-1);
    Use: state > 0 ? 'on' : 'off';

Method 1

You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check})

But anyway it is bad practice to do it this way. Much better to move it to separate method and don’t write callbacks directly in markup.

Upd: As pointed out in comments this approach might lead to unexpected results since React’s state is asynchronous. The correct way in this case will be to use callback:

this.setState(({ check }) => ({ check: !check }));

Method 2

Set: const [state, setState] = useState(1);

Toggle: setState(state*-1);

Use: state > 0 ? 'on' : 'off';

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment