I was wondering if there is a way to nest routes in react in that Navbar
is to become the parent component of dashboard and properties
<Router> <Routes> <Route path='/' element={<Home />} /> <Route path='/login' element={<Login />} /> <Route path='/signup' element={<Signup />} /> <div> <Navbar /> <div> <Route path='/dashboard' element={<Dashboard />} /> <Route path='/properties' element={<Dashboard />} /> </div> </div> </Routes> </Router>
Just like you would do in Vue router
const routes = [ { path: '/user/:id', component: User, children: [ { // UserProfile will be rendered inside User's <router-view> // when /user/:id/profile is matched path: 'profile', component: UserProfile, }, { // UserPosts will be rendered inside User's <router-view> // when /user/:id/posts is matched path: 'posts', component: UserPosts, }, ], }, ]
Advertisement
Answer
Yes, create a layout route that renders the Navbar
component and an Outlet
for nested routes.
Example:
import { Outlet } from 'react-router-dom'; const NavbarLayout = () => ( <> <Navbar /> <Outlet /> </> ); export default NavbarLayout;
…
import NavbarLayout from '../path/to/NavbarLayout'; ... <Router> <Routes> <Route path='/' element={<Home />} /> <Route path='/login' element={<Login />} /> <Route path='/signup' element={<Signup />} /> <Route element={<NavbarLayout />}> <Route path='/dashboard' element={<Dashboard />} /> <Route path='/properties' element={<Dashboard />} /> </Route> </Routes> </Router>
If you wanted to achieve the same thing using a routes config object:
const appRoutes = [ { path: "/", element: <Home />, }, { path: "/login", element: <Login />, }, { path: "/signup", element: <Signup />, }, { element: <NavbarLayout />, children: [ { path: "/dashboard", element: <Dashboard />, }, { path: "/properties", element: <Dashboard />, }, ], }, ];
…
import { useRoutes } from 'react-router-dom'; import appRoutes from '../path/to/appRoutes'; ... const routes = useRoutes(appRoutes); ... return ( ... {routes} ... );
Documentation: