1

I would like my <Link>s to have an active class when they match their route. Currently the resulting <a> tag doesn't change, even when I'm on the route referenced by the link.

My links are created like this: <Link to="/status">STATUS</Link>

The routes:

  <Router>
    <Route path='/' component={App}>
      <IndexRoute component={Status} />
      <Route path='about' component={About}/>
      <Route path='status' component={Status}/>
      <Route path='settings' component={Settings}/>
    </Route>
  </Router>

Does this feature even exist? If so, what do I need to change for it to work.

PS: I'm using react-router with redux-router. I also use the default HashHistory because it's a nwjs-app

cgross
  • 1,932
  • 2
  • 15
  • 20

2 Answers2

4

Use the activeClassName property to specify the class to add when the link is active.

<Link to="/status" activeClassName="active">STATUS</Link>
flurry
  • 506
  • 4
  • 16
2

I was having a similar problem with react-router-dom version 4.2.2. Instead of the Link component, I was able to use the NavLink component which includes the activeClassName prop.

From the documents:

NavLink: A special version of the that will add styling attributes to the rendered element when it matches the current URL.

Here is a code sample:

<ul className="menu col-sm-12">
  <li><NavLink to={`/events`} activeClassName="current">Events</NavLink></li>
</ul>

Note: activeClassName was removed from the Link component in React Router v4 (relevant answer).

Alex Johnson
  • 1,504
  • 13
  • 20