React router Link; activeClassName not working

<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>

from ReactTraining did it for me


It's hard to debug without seeing the complete code but problems with React Router activeClassName can often be solved by either:

  • Making sure that you have one IndexLink:

    <li><IndexLink to="/" activeClassName="active">Home</IndexLink></li> <li><Link to="/" activeClassName="active">About</Link></li> <li><Link to="/" activeClassName="active">Contact</Link></li>

  • Or using the onlyActiveOnIndex attribute on all Links:

    <li><Link to="/" activeClassName="active" onlyActiveOnIndex>Home</Link></li> <li><Link to="/" activeClassName="active" onlyActiveOnIndex>About</Link></li> <li><Link to="/" activeClassName="active" onlyActiveOnIndex>Contact</Link></li>

Here is a working demo of a second solution: http://codepen.io/PiotrBerebecki/pen/qaKqRW


Had the same issue! Resolved by wrapping the parent component via withRouter. E.g.

import { withRouter } from 'react-router';

class NavBar extends Component {
    ...
}

export default withRouter(NavBar);

Instructions

  1. Use <NavLink> instead of <Link> and add exact as a property

  2. Include exact as a property to ensure activeClassName only triggers on url paths that match your location exactly

Example

<NavLink exact activeClassName="active" to="/path1">
<NavLink exact activeClassName="active" to="/path2">

Source

https://reacttraining.com/react-router/web/api/NavLink/exact-bool

exact: bool

When true, the active class/style will only be applied if the location is matched exactly.