Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle boolean state in React and TypeScript?

I am new to React and TypeScript.

I want to toggle a boolean state (true/false) with a handler function. I've read other posts about how to do this in ES6 but I am unclear of how to achieve this in TypeScript.

So far I have:

  const MyComponent = () => {
    const [collapseUpper, setCollapseUpper] = React.useState(true);

    const handleCollapse = () => {
      collapseUpper = !setCollapseUpper;
    };

    return (
       <Link onClick={handleCollapse}>More</Link>
       <Collapse in={collapseUpper}>
         //content

But I cannot get it to work.

Can anyone point me in the right direction?

like image 652
MeltingDog Avatar asked Sep 09 '26 05:09

MeltingDog


1 Answers

This is how it should be done:

const handleCollapse = () => {
  setCollapseUpper(!collapseUpper);
};

You will need to call the setCollapseUpper to handle any updates in state.

Better still, you can use the callback function to update the state:

const handleCollapse = () => {
  setCollapseUpper((prevState) => !prevState);
};
like image 178
wentjun Avatar answered Sep 11 '26 19:09

wentjun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!