From 8aa0edb0b815e1e2e32db2f3e3a3e7423bd2acb8 Mon Sep 17 00:00:00 2001 From: Matt Brophy Date: Mon, 13 Mar 2023 11:37:29 -0400 Subject: [PATCH] Fix route ID generation when using Fragments in createRoutesFromElements --- .changeset/fix-fragments-ids.md | 5 ++ .../createRoutesFromChildren-test.tsx | 54 +++++++++++++++++++ packages/react-router/lib/components.tsx | 5 +- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 .changeset/fix-fragments-ids.md diff --git a/.changeset/fix-fragments-ids.md b/.changeset/fix-fragments-ids.md new file mode 100644 index 0000000000..b6d8cc21b4 --- /dev/null +++ b/.changeset/fix-fragments-ids.md @@ -0,0 +1,5 @@ +--- +"react-router": patch +--- + +Fix route ID generation when using Fragments in `createRouteFromElements` diff --git a/packages/react-router/__tests__/createRoutesFromChildren-test.tsx b/packages/react-router/__tests__/createRoutesFromChildren-test.tsx index c1ab7fc109..2d18fd2c7a 100644 --- a/packages/react-router/__tests__/createRoutesFromChildren-test.tsx +++ b/packages/react-router/__tests__/createRoutesFromChildren-test.tsx @@ -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( + + + <> + + <> + + + + + + + + ) + ).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, + }, + ], + }, + ]); + }); }); diff --git a/packages/react-router/lib/components.tsx b/packages/react-router/lib/components.tsx index df8e30e3f5..efa75820be 100644 --- a/packages/react-router/lib/components.tsx +++ b/packages/react-router/lib/components.tsx @@ -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; } @@ -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,