react-bootstrap how to collapse menu when item is selected

Chris G. picture Chris G. · Sep 8, 2015 · Viewed 25.4k times · Source

How do you make the menu collapse after item is selected?

I dont know how to make it work on fiddle, but this is what I would do? https://jsfiddle.net/vjeux/kb3gN/

import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, DropdownButton, MenuItem, CollapsibleNav} from 'react-bootstrap';

export default class App extends React.Component {

    constructor(props) {
      super(props);
      this.onSelect = this.onSelect.bind(this);
      this.toggleNav = this.toggleNav.bind(this);
      // this.state = {navExpanded: false};
    }

    onSelect(e){
        console.log('OnSelect')
        // console.log(this.state.navExpanded);
        // this.setState({navExpanded: false});
    }

    toggleNav(){console.log('toggle...')};

    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} onToggle={() => this.toggleNav()}>
    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} >

    render() {
        return (

          <Navbar inverse fixedTop toggleNavKey={0} >
            <Nav right eventKey={0} onSelect={this.onSelect} > {/* This is the eventKey referenced */}
              <NavItem eventKey={1} href="#">Link</NavItem>
              <NavItem eventKey={2} href="#">Link</NavItem>
            </Nav>
          </Navbar>     

      )

    }

    componentDidMount() {

    }
}

React.render(<App />, document.getElementById('example'));

Answer

Josep Vidal picture Josep Vidal · Oct 23, 2019

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.