Skip to content
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
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