activeClassName in react router is highlighting two NavLinks at the same time
The Navlink
also needs an exact on it... Change to this:
import React, { Component } from 'react';import { NavLink } from 'react-router-dom';class Navigation extends Component { render() { return ( <div> <p> My Navigation component </p> <nav> <ul> <li><NavLink to='/' activeClassName="current" exact={true}> Home </NavLink> </li> <li><NavLink to='/about' activeClassName="current"> About </NavLink> </li> <li><NavLink to='/contact' activeClassName="current"> Contact </NavLink> </li> </ul> </nav> </div> ); }}export default Navigation;
You should add the exact
property to your root("") Route, otherwise, it will match every route starting with "", React Router exact
eg:
<Route exact path="/" component={Home} /><Route path="/about" component={About} /><Route path="/topics" component={Topics} />
Update:
Also changing the order will have same effect without exact property
<Route path="/about" component={About} /><Route path="/topics" component={Topics} /><Route path="/" component={Home} />
in side a router switch it will go to the first matching route, if we add a route with path /
at the beginning it will always render the component in the path, it is better avoid exact fix with order
Remove activeClassName
and activeStyle
props from <NavLink />
As of v6.0.0-beta.3, the activeClassName
and activeStyle
props have been removed from NavLinkProps
. Instead, you can pass a function to either style
or className
that will allow you to customize the inline styling
or the class string
based on the component's active state
.
className
<NavLink to="/" className={({ isActive }) => "nav-link" + (isActive ? " activated" : "")}> Home</NavLink>
style
<NavLink to="/" style={({ isActive }) => ({ color: isActive ? 'green' : 'blue' })}> Home</NavLink>