Blog>
Snippets

Setting Up Nested Routes in TanStack Router

Illustrate the process of configuring nested routes with TanStack Router, including tips on preserving UI hierarchy and passing route-specific data to child components.
import { createBrowserRouter, RouterProvider, Outlet } from 'tanstack-router';
Firstly, import necessary functions and components from 'tanstack-router'. 'Outlet' is used to render child routes.
const userRoutes = {
  path: 'users',
  element: <Users />,
  children: [
    { path: ':userId', element: <UserProfile /> },
    { path: ':userId/edit', element: <EditUser /> }
  ]
};
Define the child routes of the 'users' path. The 'children' array includes routes for a user profile and editing a user profile. These will be nested within the 'users' path.
const routes = [
  { 
    path: '/', 
    element: <Home />, 
    children: [userRoutes] 
  }
];
Set up the main routes array, nesting the 'userRoutes' within the home ('/') route as its children. This keeps the UI hierarchy intact.
const router = createBrowserRouter(routes);
Create a router instance by passing the 'routes' array to 'createBrowserRouter'. This initializes the router with our configured routes.
function App() {
  return <RouterProvider router={router} />;
}
Lastly, in your main App component, render the 'RouterProvider' passing in the 'router' instance. This makes the router available throughout the application.