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 ie 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 })
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!
setState
has a second form you can use if you want the state to depend on the previous state.
I suppose this is something like what you're after:
constructor(props) {
super(props);
this.state = {
expanded: false
};
}
toggleExpanded = () => {
this.setState((prevState) => ({
expanded: !prevState.expanded ? 'expanded' : false
}));
};
render() {
return (
<Nav.Toggle
onClick={this.toggleExpanded}
/>
);
}
However, I'd recommend you to stick to one type. Either boolean or string. With a boolean, the setState callback would simply be as (prevState) => ({ expanded: .prevState.expanded })
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.