if else react one-liner

I want to change the state of a Nav.Toggle in react-bootstrap. c

Currently, I have got it to open when clicked but I would like it to close i.e. this.setState({ expanded: false}) when clicked if the current state is "expanded".

My onClick handler looks as such:

onClick={() => (this.state.expanded ? false : this.setState({ expanded: "expanded" }))}

How do I make it say else if this.state.expanded ? "expanded" : this.setState({ expanded: false })?

I assume I should move this logic above the render method so bonus points if you can show me how to do it under this line as well:

constructor(props) {
        super(props);
        this.state = {
            expanded: false
        };
    }

handleNavToggle => ???

Thanks!

Answer

So if it’s a boolean initially, you can just put exclamation mark in front of it.

onClick={() => this.setState(() => ({expanded: !this.state.expanded}))}

this way it will become true or false back and forth.

Edit: Don’t forget to return as an object so you need open to normal paranthesis before curly braces.