Auto-closing the hamburger menu in React-Bootstrap
posted 2022.03.15 by Clark Wilkins

I just finished considerable research to find a working way to have the mobile version of the React Bootstrap NavBar collapse back down after you make a menu selection, and found the answer here. To summarize, we are using a NavBar collape condition stored in state and toggling it true to make the expanded menu go away.

All edits are done in App.js. Here are some "takeaway" points

  • In line 1: import { useState } from "react";.
  • Right after you start the actual App function, add:
    const [expanded, setExpanded] = useState( false );
    as the menu condition, kept in State.
  • Add this attribute to <Navbar>:
    expanded={expanded}
    Note it references the above State value.
  • Add this attribute to <Navbar.collapse>:
    onClick={ () => setExpanded( expanded ? false : "expanded" ) }
    to toggle the State value.
  • Add this onClick attribute to each link (menu item):
    onClick={() => setExpanded(false)}
    By tying it to the specific item, you can use drop-down menus (click) and not toggle the entire Navbar before you get to the menu item you want.

It's a simple and elegant solution, but hard to find in the noisy Stack Overflow environment, so I reposted it here.