Blog>
Snippets

Implementing Nested Routes

Showcase how to set up nested routes using TanStack Router, including a parent route with child routes for an organized routing structure.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
First, import the necessary components from TanStack Router.
const childLoader = async () => {
  // Logic to fetch data for the child route
};
Define a loader function for the child route if you need to fetch data.
const router = createBrowserRouter([
  {
    path: '/',
    element: <ParentComponent />, // Your parent component
    children: [
      {
        path: 'child',
        element: <ChildComponent />, // Your child component
        loader: childLoader // Optional loader for data fetching
      }
    ]
  }
]);
Set up the router with a parent route. The parent route includes a child route, which can optionally use a loader function for data fetching.
function App() {
  return <RouterProvider router={router} />;
}
Create a function component for your app and use the RouterProvider to pass the router configuration. This initializes the routing for your application.