Skip to content

Commit

Permalink
Fix route ID generation when using Fragments in createRoutesFromEleme…
Browse files Browse the repository at this point in the history
…nts (#10193)
  • Loading branch information
brophdawg11 authored Mar 15, 2023
1 parent 6c68e1e commit af4b07d
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/fix-fragments-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Fix route ID generation when using Fragments in `createRouteFromElements`
54 changes: 54 additions & 0 deletions packages/react-router/__tests__/createRoutesFromChildren-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,58 @@ describe("creating routes from JSX", () => {
);
}).toThrow("An index route cannot have child routes.");
});

it("supports react fragments for automatic ID generation", () => {
expect(
createRoutesFromChildren(
<Route path="/">
<Route index />
<>
<Route path="a">
<>
<Route path="1" />
<Route path="2" />
</>
</Route>
<Route path="b" />
</>
</Route>
)
).toEqual([
{
id: "0",
path: "/",
hasErrorBoundary: false,
children: [
{
id: "0-0",
index: true,
hasErrorBoundary: false,
},
{
id: "0-1-0",
path: "a",
hasErrorBoundary: false,
children: [
{
id: "0-1-0-0-0",
path: "1",
hasErrorBoundary: false,
},
{
id: "0-1-0-0-1",
path: "2",
hasErrorBoundary: false,
},
],
},
{
id: "0-1-1",
path: "b",
hasErrorBoundary: false,
},
],
},
]);
});
});
5 changes: 3 additions & 2 deletions packages/react-router/lib/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -570,11 +570,13 @@ export function createRoutesFromChildren(
return;
}

let treePath = [...parentPath, index];

if (element.type === React.Fragment) {
// Transparently support React.Fragment and its children.
routes.push.apply(
routes,
createRoutesFromChildren(element.props.children, parentPath)
createRoutesFromChildren(element.props.children, treePath)
);
return;
}
Expand All @@ -591,7 +593,6 @@ export function createRoutesFromChildren(
"An index route cannot have child routes."
);

let treePath = [...parentPath, index];
let route: RouteObject = {
id: element.props.id || treePath.join("-"),
caseSensitive: element.props.caseSensitive,
Expand Down

0 comments on commit af4b07d

Please sign in to comment.