3

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?

3
  • 1
    setCollapseUpper is a function not a value Commented Jun 17, 2020 at 4:39
  • You need to invoke it setCollapseUpper(!collapseUpper) Commented Jun 17, 2020 at 4:40
  • Read here reactjs.org/docs/hooks-reference.html#usestate Commented Jun 17, 2020 at 4:41

2 Answers 2

6

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);
};
Sign up to request clarification or add additional context in comments.

Comments

1

you need to change the value of collapseUpper not setCollapseUpper:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.