Reputation: 9785
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
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.
The element to render when the route matches the URL.
<Route path="/for-sale" element={<Properties />} />
(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 element
s are the content to render.
Upvotes: 2