Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :(

like image 546
pete Avatar asked Jan 13 '16 16:01

pete


2 Answers

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.

like image 61
taion Avatar answered Oct 05 '22 18:10

taion


With <LinkContainer>, there's no need for the eventKey, so it can be removed. Doing so will have the active handled properly.

So you end up with

  <Navbar>
    <Nav>
      <LinkContainer to="/">
        <NavItem>Home</NavItem>
      </LinkContainer>
      <LinkContainer to="/login">
        <NavItem>Login</NavItem>
      </LinkContainer>
      ...
    </Nav>
  </Navbar>
like image 43
pdeschen Avatar answered Oct 05 '22 18:10

pdeschen