Skip to content

Commit

Permalink
Layout routes don't match
Browse files Browse the repository at this point in the history
Fixes #8085
  • Loading branch information
mjackson committed Oct 3, 2021
1 parent 3b54be1 commit 6ab98d3
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
31 changes: 31 additions & 0 deletions packages/react-router/__tests__/layout-routes-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as React from "react";
import { create as createTestRenderer } from "react-test-renderer";
import { MemoryRouter as Router, Routes, Route, Outlet } from "react-router";

describe("A layout route", () => {
it("does not match when none of its children do", () => {
let renderer = createTestRenderer(
<Router initialEntries={["/"]}>
<Routes>
<Route
element={
<div>
<h1>Layout</h1>
<Outlet />
</div>
}
>
<Route path="/home" element={<h1>Home</h1>} />
</Route>
<Route index element={<h1>Index</h1>} />
</Routes>
</Router>
);

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<h1>
Index
</h1>
`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe("nested routes with no path", () => {
<Routes>
<Route element={<First />}>
<Route element={<Second />}>
<Route element={<Third />} />
<Route path="/" element={<Third />} />
</Route>
</Route>
</Routes>
Expand Down
20 changes: 19 additions & 1 deletion packages/react-router/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,18 @@ export interface RouteProps {
path?: string;
}

export interface PathRouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactElement | null;
path: string;
}

export interface LayoutRouteProps {
children?: React.ReactNode;
element?: React.ReactElement | null;
}

export interface IndexRouteProps {
element?: React.ReactElement | null;
index: true;
Expand All @@ -214,7 +226,7 @@ export interface IndexRouteProps {
* @see https://reactrouter.com/api/Route
*/
export function Route(
_props: RouteProps | IndexRouteProps
_props: PathRouteProps | LayoutRouteProps | IndexRouteProps
): React.ReactElement | null {
invariant(
false,
Expand Down Expand Up @@ -830,6 +842,12 @@ function flattenRoutes(
flattenRoutes(route.children, branches, routesMeta, path);
}

// Routes without a path shouldn't ever match by themselves unless they are
// index routes, so don't add them to the list of possible branches.
if (route.path == null && !route.index) {
return;
}

branches.push({ path, score: computeScore(path), routesMeta });
});

Expand Down

0 comments on commit 6ab98d3

Please sign in to comment.