Blog>
Snippets

Defining Nested Routes with TanStack Router

Show how to define nested routes in a React application using TanStack Router, including parent and child routes for a seamless navigation experience.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Layout from './components/Layout';
import HomePage from './components/HomePage';
import AboutPage from './components/AboutPage';
import UserProfile from './components/UserProfile';

// Define the route configuration
const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />, // This acts as the parent component
    children: [
      { path: '/', element: <HomePage /> },
      { path: 'about', element: <AboutPage /> },
      { path: 'profile/:userId', element: <UserProfile /> }
    ]
  }
]);
This code block creates a React Router configuration using TanStack Router. First, it imports necessary components and the `createBrowserRouter` and `RouterProvider` from `react-router-dom`. It demonstrates setting up a parent `Layout` route component that wraps the `HomePage`, `AboutPage`, and `UserProfile` components, illustrating the concept of nested routing. The `UserProfile` route is dynamic, indicated by `:userId`, which makes it possible to fetch user profiles dynamically based on the URL parameter.
import React from 'react';
import { RouterProvider } from 'react-router-dom';
import { router } from './routerConfig'; // Assume the router configuration is exported from './routerConfig'

function App() {
  return (
    <RouterProvider router={router} />
  );
}
This snippet demonstrates how to integrate the TanStack Router configuration into a React application. It imports the `RouterProvider` component from `react-router-dom` and the previously defined router configuration. The `RouterProvider` is then used in the `App` component, passing the `router` as a prop to enable routing throughout the application. This integration step is essential for activating the nested route configuration in the React app.