react-router index route always active
You can use <IndexLink>
or set onlyActiveOnIndex
prop for links that are not to be highlighted when their children paths are active:
<li className="headerNavLink"><IndexLink to="/" activeClassName="activeLink">introduction</IndexLink></li>
or
<li className="headerNavLink"><Link to="/" activeClassName="activeLink" onlyActiveOnIndex>introduction</Link></li>
Just like also to share this if you use "react-router-dom": "4.1.1",
export const routes = <Index>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</Index>;
Then your navigation menu is
<NavLink exact={true} activeClassName='active' to="/">
Home
</NavLink>
<NavLink activeClassName='active' to="/bout">
About
</NavLink>
Just specify also the "exact={true}" props for the NavLink and it should work as expected.
Thanks, Hope this helps.
I'd like to reference the docs for React Router (react-router-dom
, currently v5) and the sources.
This is the up-to-date way to implement this:
exact: bool
When true, the active class/style will only be applied if the location is matched exactly.
<NavLink exact to="/profile">
Profile
</NavLink>
Here is a real world working example:
<ul class="nav flex-column">
<li class="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/" exact>Home</NavLink>
</li>
<li class="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/calendar">Calendar</NavLink>
</li>
<li class="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/page">Page</NavLink>
</li>
</ul>