react-bootstrap how to collapse menu when item is selected
i have found the solution from this link https://github.com/react-bootstrap/react-bootstrap/issues/1301
i will put sample code of the link above here
const Menu = React.createClass ({
getInitialState () {
return {
navExpanded: false
}
},
setNavExpanded(expanded) {
this.setState({ navExpanded: expanded });
},
closeNav() {
this.setState({ navExpanded: false });
},
render() {
return (
<div>
<Navbar onToggle={this.setNavExpanded}
expanded={this.state.navExpanded}>
<Navbar.Header>
<Navbar.Brand>
<Link to="some url">Main</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav onSelect={this.closeNav}>
{ this.renderMenuItem() }
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
)
}
For anyone coming here in 2020 and using Hooks, maybe you are using react-router
, and as result, instead of the Nav.Link
that are the default component for the Navbar you use Link
from react-router
.
And what did you find? That in result the mobile menu is not working as expected and not closing after clicking on a link, and nothing seems to work.
Here is my "simple" solution (Using hooks) to that problem:
First we set up a hook:
const [expanded, setExpanded] = useState(false);
Second in the Navbar
we add this prop:
<Navbar expanded={expanded}>
Now we have control over the visibilty of the menu, in the "first" load it will be hidden.
Third we add an onClick
event to the toggle handler that changes the menu visibility status:
<Navbar.Toggle onClick={() => setExpanded(expanded ? false : "expanded")} />
Fourth we add the prop onClick={() => setExpanded(false)}
to all our Link
components from react-router inside our Navbar.
Profit! I swear that after more than 1 hour wandering for the internet is the easiest and cleanest solution I found.