Categories
React Answers

How to toggle the boolean state of a React component?

Spread the love

Sometimes, we want to toggle the boolean state of a React component.

In this article, we’ll look at how to toggle the boolean state of a React component.

How to toggle the boolean state of a React component?

To toggle the boolean state of a React component, we can call the state setter function with a function that returns the latest boolean value.

For instance, we write

const Comp = () => {
  const [check, setCheck] = useState(false);
  // ...
  const toggle = () => {
    setCheck((prevCheck) => !prevCheck);
  };

  //...
};

to create the check state in the Comp component.

Then we add the toggle function that calls setCheck with a function that returns the original value of the check state, which is prevCheck, negated to set check to the negated value of prevCheck.

Conclusion

To toggle the boolean state of a React component, we can call the state setter function with a function that returns the latest boolean value.

For instance, we write

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *