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)} />
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.