From 40ccb321c62c4a821f20579de5ad3b714c504e54 Mon Sep 17 00:00:00 2001 From: James Gelok Date: Fri, 5 Nov 2021 12:10:49 -0400 Subject: [PATCH] Warn Against Non-Route children --- .../react-router/__tests__/Routes-test.tsx | 35 +++++++++++++++++++ packages/react-router/index.tsx | 7 ++++ 2 files changed, 42 insertions(+) diff --git a/packages/react-router/__tests__/Routes-test.tsx b/packages/react-router/__tests__/Routes-test.tsx index 4bc123f4f..e45df9e52 100644 --- a/packages/react-router/__tests__/Routes-test.tsx +++ b/packages/react-router/__tests__/Routes-test.tsx @@ -4,12 +4,15 @@ import { MemoryRouter, Routes, Route } from "react-router"; describe("", () => { let consoleWarn: jest.SpyInstance; + let consoleError: jest.SpyInstance; beforeEach(() => { consoleWarn = jest.spyOn(console, "warn").mockImplementation(() => {}); + consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); }); afterEach(() => { consoleWarn.mockRestore(); + consoleError.mockRestore(); }); it("renders null and issues a warning when no routes match the URL", () => { @@ -110,4 +113,36 @@ describe("", () => { `); }); + + it("throws if some is passed as a child of ", () => { + const CustomRoute = (...args: any) => ; + + expect(() => { + TestRenderer.create( + + + Home} /> + Admin} /> + + + ); + }).toThrow(/children of must be a /); + + expect(consoleError).toHaveBeenCalledTimes(1); + }); + + it("throws if a regular element (ex:
) is passed as a child of ", () => { + expect(() => { + TestRenderer.create( + + + Home} /> +
Admin } as any)} /> + + + ); + }).toThrow(/children of must be a /); + + expect(consoleError).toHaveBeenCalledTimes(1); + }); }); diff --git a/packages/react-router/index.tsx b/packages/react-router/index.tsx index cf73edaea..5f13f306c 100644 --- a/packages/react-router/index.tsx +++ b/packages/react-router/index.tsx @@ -704,6 +704,13 @@ export function createRoutesFromChildren( return; } + invariant( + element.type === Route, + `[${ + typeof element.type === "string" ? element.type : element.type.name + }] is not a component. All component children of must be a or ` + ); + let route: RouteObject = { caseSensitive: element.props.caseSensitive, element: element.props.element,