Search code examples
twitter-bootstrapreactjsreact-routerreact-bootstrap

How to handle .active state in React-Bootstrap's Nav NavItem, with React-Router


I'm using using React with react-router 2.0.0-rc4, react-bootstrap 0.28.2, and react-router-bootstrap 0.20.1. I have the nav bar mostly working with the following structure, but the .active class is not applied correctly:

  <Navbar>
    <Nav activeKey={ this.state.selectedKey } onSelect={ this._onSelect } >
      <LinkContainer to="/">
        <NavItem eventKey={1}>Home</NavItem>
      </LinkContainer>
      <LinkContainer to="/login">
        <NavItem eventKey={2}>Login</NavItem>
      </LinkContainer>
      ...
    </Nav>
  </Navbar>

The problem is that the .active class is not unset as I move between the menu items. So, if I click NavItem 2, both items become active (no matter what this.state.selectedKey is set to). I have a larger menu and all nav items get set as active when any menu item is clicked. What am I missing?

I do not think this Q is a duplicate of this post because the React-Bootstrap components are supposed to manage the active state automatically via the activeKey prop, but.. the docs do not show a clear example of this, so, confused :(


Solution

  • If your routes look like

    <Route path="/">
      <Route path="login" />
    </Route>
    

    Then you'll want to use <IndexLinkContainer> rather than <LinkContainer> for the to="/" link.