How to Update NavLink Component in React
This article provides a straightforward guide on how to update and
implement the NavLink component in React, focusing on the
modern standards introduced in React Router v6. You will learn how the
component’s API has changed from older versions and how to dynamically
apply active classes and styles using the updated function-based prop
syntax.
In older versions of React Router (v5 and below), the
NavLink component used specific props like
activeClassName and activeStyle to style the
active link. In React Router v6, these props were deprecated and
removed. Instead, NavLink now uses a function-based
approach for its className and style
props.
Updating className for Active Links
To apply a custom CSS class when a link is active in React Router v6,
you must pass a function to the className prop. This
function receives an object containing an isActive boolean
property, which you can destructure to conditionally apply your
classes.
import { NavLink } from 'react-router-dom';
function Navigation() {
return (
<NavLink
to="/dashboard"
className={({ isActive }) =>
isActive ? 'nav-link active' : 'nav-link'
}
>
Dashboard
</NavLink>
);
}Updating Inline Styles for Active Links
Similarly, if you prefer inline styling, the style prop
also accepts a function that receives the isActive state.
You can use this to return different style objects depending on whether
the link is active.
import { NavLink } from 'react-router-dom';
function Navigation() {
return (
<NavLink
to="/profile"
style={({ isActive }) => ({
color: isActive ? 'blue' : 'black',
fontWeight: isActive ? 'bold' : 'normal',
})}
>
Profile
</NavLink>
);
}Managing Matching Logic with the end Prop
In previous versions, the exact prop was used to ensure
a link was only marked active if the URL matched perfectly. In the
updated React Router, this prop has been replaced by the
end prop.
Adding the end prop ensures that the link is not
highlighted as active when descendants of the route are matched.
<NavLink
to="/"
end
className={({ isActive }) => isActive ? 'active' : ''}
>
Home
</NavLink>