Skip to content

Commit

Permalink
Make <NavLink> match only whole URL segments
Browse files Browse the repository at this point in the history
Fixes #7523
  • Loading branch information
mjackson committed Oct 2, 2021
1 parent 85a45bb commit 3b54be1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
26 changes: 26 additions & 0 deletions packages/react-router-dom/__tests__/nav-link-active-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,32 @@ describe("NavLink", () => {
});
});

describe("when it matches a partial URL segment", () => {
it("does not apply the 'active' className to the underlying <a>", () => {
let renderer = createTestRenderer(
<Router initialEntries={["/home/children"]}>
<Routes>
<Route
path="home"
element={
<div>
<NavLink to="child">Home</NavLink>
<Outlet />
</div>
}
>
<Route path="children" element={<div>Child</div>} />
</Route>
</Routes>
</Router>
);

let anchor = renderer.root.findByType("a");

expect(anchor.props.className).not.toMatch("active");
});
});

describe("when it matches just the beginning but not to the end", () => {
it("applies the default 'active' className to the underlying <a>", () => {
let renderer = createTestRenderer(
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,11 @@ export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
toPathname = toPathname.toLowerCase();
}

let isActive = end
? locationPathname === toPathname
: locationPathname.startsWith(toPathname);
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/");

let ariaCurrent = isActive ? ariaCurrentProp : undefined;

Expand Down

0 comments on commit 3b54be1

Please sign in to comment.