Blog>
Snippets

Implementing Nested Routes with TanStack Router

Show how to create nested routes in a project using TanStack Router, for example, a user profile page with nested routes for user's posts and settings.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack-router';
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import UserProfile from './UserProfile';
import UserPosts from './UserPosts';
import UserSettings from './UserSettings';
First, import all necessary components from 'tanstack-router', React, and your component files. 'createBrowserRouter' is used to create the router, 'RouterProvider' to provide the router context, and 'Route' to define each route.
const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: 'profile',
        element: <UserProfile />, // Parent route for user's profile
        children: [
          { path: 'posts', element: <UserPosts /> }, // Nested route for user's posts
          { path: 'settings', element: <UserSettings /> } // Nested route for user's settings
        ]
      }
    ]
  }
]);
Define your routes using a nested structure. Here, 'UserProfile' is a parent route, and it has two child routes: 'UserPosts' and 'UserSettings'. This structure allows for a clean organization of nested routes.
const root = createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);
Finally, initialize the router with 'RouterProvider' and render your app. This step activates the router and makes it available throughout your application.