Skip to content

Commit 5ec32d2

Browse files
authored
fix: Fix navigate bug from nested index routes (#8965)
1 parent c19f13e commit 5ec32d2

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

packages/react-router/__tests__/navigate-test.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,5 +192,30 @@ describe("<Navigate>", () => {
192192
</h1>
193193
`);
194194
});
195+
196+
it("handles relative navigation from nested index route", () => {
197+
let renderer: TestRenderer.ReactTestRenderer;
198+
TestRenderer.act(() => {
199+
renderer = TestRenderer.create(
200+
<MemoryRouter initialEntries={["/layout/thing"]}>
201+
<Routes>
202+
<Route path="layout">
203+
<Route path=":param">
204+
{/* redirect /layout/:param/ index routes to /layout/:param/dest */}
205+
<Route index element={<Navigate to="dest" />} />
206+
<Route path="dest" element={<h1>Destination</h1>} />
207+
</Route>
208+
</Route>
209+
</Routes>
210+
</MemoryRouter>
211+
);
212+
});
213+
214+
expect(renderer.toJSON()).toMatchInlineSnapshot(`
215+
<h1>
216+
Destination
217+
</h1>
218+
`);
219+
});
195220
});
196221
});

packages/react-router/lib/hooks.tsx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,16 +155,14 @@ export function useNavigate(): NavigateFunction {
155155
let { matches } = React.useContext(RouteContext);
156156
let { pathname: locationPathname } = useLocation();
157157

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

164-
if (matches.length > 0 && matches[matches.length - 1].route.index) {
165-
pathContributingMatches.pop();
166-
}
167-
168166
let routePathnamesJson = JSON.stringify(
169167
pathContributingMatches.map((match) => match.pathnameBase)
170168
);

0 commit comments

Comments
 (0)