Blog>
Snippets

Nested Routing with TanStack Router

Provide an example of nested routing, where a main component has child components with their own sub-paths, illustrating a case with a dashboard layout having nested views.
import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom';
import { Dashboard, Overview, Reports } from './components';
Imports necessary components from react-router-dom and the components used in the dashboard.
const dashboardRoutes = {
  path: 'dashboard',
  element: <Dashboard />, // Parent route component
  children: [
    { path: 'overview', element: <Overview /> }, // Nested route
    { path: 'reports', element: <Reports /> } // Another nested route
  ]
};
Defines a parent route for the dashboard and nested routes for its children (overview and reports pages).
const router = createBrowserRouter([
  dashboardRoutes // Adds the dashboard route configuration to the router
]);
Creates a browser router instance with the defined dashboard routes.
function App() {
  return <RouterProvider router={router} />;
}
Defines the root component where the RouterProvider wraps the app with the router instance, enabling routing within the application.
function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet /> {/* Renders the matched child route component */}
    </div>
  );
}
The Dashboard component acts as a layout for its child routes, using the Outlet component to render them.