Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed NavLink Issue #10734

Merged
merged 12 commits into from
Oct 31, 2023
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,4 @@
- smithki
- istarkov
- louis-young
- bilalk711
27 changes: 27 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 @@ -397,6 +397,33 @@ describe("NavLink", () => {
expect(anchor.props.className).toMatch("active");
});

bilalk711 marked this conversation as resolved.
Show resolved Hide resolved
it("In case of trailing slash with no further ", () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/home/child"]}>
<Routes>
<Route
path="home"
element={
<div>
<NavLink to="/home/">Home</NavLink>
<Outlet />
</div>
}
>
<Route path="child" element={<div>Child</div>} />
</Route>
</Routes>
</MemoryRouter>
);
});

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

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

describe("when end=true", () => {
it("does not apply the default 'active' className to the underlying <a>", () => {
let renderer: TestRenderer.ReactTestRenderer;
Expand Down
7 changes: 4 additions & 3 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -656,12 +656,13 @@ export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
: null;
toPathname = toPathname.toLowerCase();
}

const endSlashPosition = (toPathname.length > 1 && toPathname[toPathname.length - 1] === "/") ? toPathname.length - 1 : toPathname.length;
brophdawg11 marked this conversation as resolved.
Show resolved Hide resolved
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/");
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(endSlashPosition) === "/"
);

let isPending =
nextLocationPathname != null &&
Expand Down