In React Router Version 5 I had a NavLink
which looked the following:
<NavLink to="/notes" exact={true} className="border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" activeClassName="bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" > Home </NavLink>
It recognized both localhost:3000/notes
and localhost:3000/notes/
with a trailing slash as active urls.
In React Router Version 6 I refactored it to the following:
<NavLink to="/notes" end className={(navData) => navData.isActive ? "bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" : "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" } > Home </NavLink>
This recognizes only localhost:3000/notes
as active url.
Is there a way in v6 to have also the version with trailing slash recognized as an active url?
Answer
I think you’ve mixed up what the react-router-dom
v5 exact
prop represents, or rather, that you’ve conflated the behavior between the exact
and strict
props.
v5
exact
: Whentrue
, the active class/style will only be applied if the location is matched exactly.strict
: Whentrue
, the trailing slash on a location’s pathname will be taken into consideration when determining if the location matches the current URL. See the<Route strict>
documentation for more information.
Note the emphasis regarding exactly matching is mine.
v6
In react-router-dom
version 6 all routes/links are always exactly matched. The end
prop of the NavLink
has more to do with the trailing slash "/"
than it does route matching.
If the
end
prop is used, it will ensure this component isn’t matched as “active” when its descendant paths are matched. For example, to render a link that is only active at the website root and not any other URLs, you can use:<NavLink to="/" end> Home </NavLink>
To address your question
Why React Router NavLink prop exact (v5) vs. end (v6) lead to different result with trailing slash in url
This is because you are comparing apples to oranges. If you want to achieve the same link behavior from v5 to v6 regarding the trailing slash "/"
then omit the end
prop.
<NavLink to="/notes" className={(navData) => navData.isActive ? "bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" : "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium" } > Home </NavLink>