Blog>
Snippets

Nested Routes and Layouts with TanStack Router

Illustrate how to set up nested routes for a dashboard layout, where the dashboard serves as a parent route with child routes for various dashboard pages.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack/react-router-dom';
import DashboardLayout from './layouts/DashboardLayout';
import HomePage from './pages/HomePage';
import ProfilePage from './pages/ProfilePage';
import SettingsPage from './pages/SettingsPage';
First, import necessary components and functions from TanStack Router, along with the layout component for the dashboard and the specific page components you'll be routing to.
const router = createBrowserRouter([
  {
    path: '/',
    element: <DashboardLayout />,
    children: [
      { path: 'home', element: <HomePage /> },
      { path: 'profile', element: <ProfilePage /> },
      { path: 'settings', element: <SettingsPage /> }
    ]
  }
]);
Create the router instance using 'createBrowserRouter'. Define the dashboard as the parent route with 'DashboardLayout' as its element. The 'children' property is an array of routes corresponding to the pages within the dashboard layout.
function App() {
  return <RouterProvider router={router} />;
}
Define your application's main component. Use 'RouterProvider' from TanStack Router and pass in the 'router' instance. This setup enables your application to utilize the defined routes.