react-router
react-router copied to clipboard
[Bug]: NavLink encodes special characters differently than history
What version of React Router are you using?
react-router-dom 6.14.2
Steps to Reproduce
Use the '|' character in a dynamic segment in the to
prop for a NavLink
.
Expected Behavior
When that URL is hit (for example by clicking the NavLink
), the NavLink
becomes active.
Actual Behavior
The NavLink
is never in active state.
I debugged this a bit, and the problem is this: NavLink
does comparison between the current location (as it comes from location.pathname
) and the to
prop. They are url encoded differently, so they never match if you have the character '|' in the url.
The current location is already URL encoded, and in it, the '|' character is not encoded. The to
prop is encoded in NavLink
by this code:
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
The '|' character is encoded by navigator.encodeLocation()
(it uses new URL()
to do the encoding).
It seems like the problem appeared in version 6.4.4. I spotted this line in the 6.4.4 release notes "Fix issues with encoded characters in NavLink and descendant <Routes> (#9589, #9647)" and it seems to me like the probable source of the problem.
As a temporary solution:
<NavLink to={encodeURI(`/pathTo/${entityName}`)}>
{entityName}
<Nav/Link>