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

fix: Fix navigate bug from nested index routes #8965

Merged
merged 1 commit into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/react-router/__tests__/navigate-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,30 @@ describe("<Navigate>", () => {
</h1>
`);
});

it("handles relative navigation from nested index route", () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/layout/thing"]}>
<Routes>
<Route path="layout">
<Route path=":param">
{/* redirect /layout/:param/ index routes to /layout/:param/dest */}
<Route index element={<Navigate to="dest" />} />
<Route path="dest" element={<h1>Destination</h1>} />
</Route>
</Route>
</Routes>
</MemoryRouter>
);
});

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<h1>
Destination
</h1>
`);
});
});
});
10 changes: 4 additions & 6 deletions packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,14 @@ export function useNavigate(): NavigateFunction {
let { matches } = React.useContext(RouteContext);
let { pathname: locationPathname } = useLocation();

// Ignore pathless matches (i.e., share the same pathname as their ancestor)
// Ignore index + pathless matches
let pathContributingMatches = matches.filter(
(match, index) =>
index === 0 || match.pathnameBase !== matches[index - 1].pathnameBase
index === 0 ||
(!match.route.index &&
match.pathnameBase !== matches[index - 1].pathnameBase)
);

if (matches.length > 0 && matches[matches.length - 1].route.index) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was incorrect and should have been checking pathContributingMatches instead of matches, but instead we can just lump the index check into the filter above

pathContributingMatches.pop();
}

let routePathnamesJson = JSON.stringify(
pathContributingMatches.map((match) => match.pathnameBase)
);
Expand Down