Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: The element prop of the <Route> component should be typed as a ReactNode, not ReactElement #8456

Closed
joekrill opened this issue Dec 8, 2021 · 0 comments
Labels

Comments

@joekrill
Copy link
Contributor

joekrill commented Dec 8, 2021

What version of React Router are you using?

6.0.2

Steps to Reproduce

To reproduce: start with the "Auth Example" currently linked to in the docs, and change the RequireAuth component so the childrenprop uses the more standard ReactNode type instead of JSX.Element (line 120). You'll see a type error appear on line 44:

Screen Shot 2021-12-08 at 5 25 26 PM

Example here: https://stackblitz.com/edit/github-37enwq?file=src/App.tsx

Expected Behavior

The element prop should accept a ReactNode, not a ReactElement. Using ReactElement artificially limits what can be passed as an element when using the <Routes> and <Route> components.

At first I thought this was an intentional decision that had some underlying technical reason. But under-the-hood the <Routes> and <Route> component are implemented using the useRoutes hook. And that hook allows an element to be a ReactNode:

interface RouteObject {
  caseSensitive: boolean;
  children?: RouteObject[];
  element: React.ReactNode;
  path: string;
}

But the <Route> component is typed differently:

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

Even though under-the-hood the implementation is exactly the same (<Routes> simply calls useRoutes).

In most cases this isn't a problem. But in the case above, where you have a component that does some gating and may pass-through children, it doesn't work when children are typed in the normal way.

You can work-around this by changing how you type things, but that can cause a cascading effect in a project and require retyping a bunch of unrelated components. And it seems the official types always type children as a ReactNode, not as a JSX.Element or ReactElement (as seen in the Auth Example).

Actual Behavior

Only ReactElements can be used when defining routes using the <Route> component, artificially limiting what can be rendered there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants