I'm using react-router v6, Is it possible to use nested routes without using the Outlet component?
For example: I have a users page and onClick on a user component it should navigate to the specific user page,
Current try:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users" element={<Users />} />
<Route path=":id" element={<UserPage/>} />
</Routes>
And on click on a specific user:
const gotoUserPage = () => {
navigate('1')
}
The gotoUserPage change the URL from '/users' to '/users/1' but the userPage component doesn't render.
Is it possible to use nested routes without using the Outlet component?
No, an Outlet component is required in order to render the nested Route components.
Either the Users component must render an Outlet component, or you can render directly an Outlet as a layout component.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users" element={<Outlet />}>
<Route index element={<Users />} /> // "/users"
<Route path=":id" element={<UserPage/>} /> // "/users/:id"
</Route>
</Routes>
Though, a better or more accurate question may be, do you even need to explicitly render an Outlet as a layout element? The answer may surpisingly be "no". Route components render an Outlet by default on the element prop.
The default
<Route element>is an<Outlet>. This means the route will still render its children even without an explicit element prop, so you can nest route paths without nesting UI around the child route elements.
You can simply wrap some nested routes in a Route and specify only the path for nesting, and the nested routes will be rendered into an Outlet by default.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users">
<Route index element={<Users />} /> // "/users"
<Route path=":id" element={<UserPage/>} /> // "/users/:id"
</Route>
</Routes>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With