Septagram
Septagram

Reputation: 9785

What's the difference between "children" and "element" props

I'm upgrading to React Router 6. The migration guide suggests using the following syntax when declaring routes:

<Switch>
  <Route exact path="/">
    <Home />
  </Route>
  <Route path="/users">
    <Users />
  </Route>
</Switch>

Switch is now renamed to Routes, but that's beside the point. When trying this syntax I get an error:

<MyComponent> is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

Using element instead of component children works, but I can't find in the docs what's the difference between the element prop and component children, nor the motivation for this requirement.

Any suggestions?

Upvotes: 1

Views: 338

Answers (1)

Drew Reese
Drew Reese

Reputation: 202791

The Why does <Route> have an element prop instead of render or component of the official FAQ likely covers/explains/answers your question why the element prop exists.

The element prop is for rendering routed content, the children prop (not used directly) is only used to nest Route components, i.e. the Route component can only be rendered by the Routes component or other Route components.

element prop

The element to render when the route matches the URL.

<Route path="/for-sale" element={<Properties />} />

"children" prop

(TODO: need to talk about nesting, maybe even a separate doc)

example:

<Route path="/foo" element={<Foo />}>      // <-- "/foo"
  <Route path="bar element={<FooBar />} /> // <-- "/foo/bar"
</Route>

An easier way to see this might be to see the routes configuration "view" which uses the useRoutes hook (used by the Routes component as an implementation detail).

Example:

const routes = [
  {
    path: "/foo",
    element: <Foo />,
    children: [
      {
        path: "bar",
        element: <FooBar />,
      },
    ],
  },
];

Here's it is fairly obvious the children are the nested routes while the elements are the content to render.

Upvotes: 2

Related Questions