How to set activeClassName for wrapper element of Link or IndexLink in react-router?

You need to enclose your <li> as a router aware component:

import { Link, IndexLink } from 'react-router'

class NavItem extends React.Component {
  render () {
    const { router } = this.context
    const { index, onlyActiveOnIndex, to, children, ...props } = this.props

    const isActive = router.isActive(to, onlyActiveOnIndex)
    const LinkComponent = index ? Link : IndexLink

    return (
      <li className={isActive ? 'active' : ''}>
        <LinkComponent {...props}>{children}</LinkComponent>
      </li>
    )
  }
}

Usage:

<ul>
  <NavItem to="https://stackoverflow.com/" index={true}>Home</NavItem>
  <NavItem to='/a'>A</NavItem>
</ul>

I took inspration from the react-router-bootstrap module, https://github.com/react-bootstrap/react-router-bootstrap/blob/master/src/LinkContainer.js. I didn’t test it though so let me know how it goes.

Leave a Comment