Active link with React-Router?
<Link>
no longer has the activeClassName
or activeStyle
properties. In react-router v4 you have to use <NavLink>
if you want to do conditional styling:
const Router = () => (
<BrowserRouter>
<div>
<Nav>
<NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink>
<NavLink activeClassName='is-active' to='/about'>About</NavLink>
</Nav>
<Match pattern='/' exactly component={Home} />
<Match pattern='/about' exactly component={About} />
<Miss component={NoMatch} />
</div>
</BrowserRouter>
)
I added an exact property to the home <NavLink>
, I'm fairly sure that without it, the home link would always be active since /
would match /about
and any other pages you have.
React Router v6:
Source: Active NavLink Classes with React Router
Now you can use the className
property which now accepts a function and passes an isActive
boolean property, like this:
<NavLink
to="users"
className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
Users
</NavLink>
You can also adding multiple classes too, since v6 is out:
<NavLink
to="users"
className={({ isActive }) =>
isActive ? 'bg-green-500 font-bold' : 'bg-red-500 font-thin'
}
>
Users
</NavLink>
Live demo: Active NavLink Classes with React Router
As an addition to @Nick's answer (React Router v6), for those who needs the active navigation state in the upper context..
Conditional rendering might be a use case for the need. For ex: if it is active render the filled icon otherwise render the regular one.
This could be achieved by finding the route that we are currently in and then we can do the conditional rendering operation however it would be a little cumbersome.
Instead, we can write a function that modifies the state in Navlink
's style prop as following..
const [active, setActive] = useState('home')
const activate = (isActive, path, activeStyle, nonActiveStyle) => {
if (isActive) {
setActive(path)
return activeStyle
}
return nonActiveStyle
}
return (
<nav>
<NavLink
to="/"
style={(activeNav) => activate(activeNav.isActive, 'home')}
>
{active === 'home' ? <HomeFill /> : <Home />}
</NavLink>
<NavLink
to="/profile"
style={(activeNav) => activate(activeNav.isActive, 'profile')}
>
{active === 'profile' ? <ProfileFilled /> : <Profile />}
</NavLink>
</nav>
)