Blog>
Snippets

Implementing Nested Routes in TanStack Router

Example of setting up nested routes, allowing component-based structuring for complex applications.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import React from 'react';
import ReactDOM from 'react-dom/client';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import Post from './components/Post';
import Layout from './components/Layout';
Import necessary components and functions from 'react-router-dom' and other component files.
const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />, // Parent route
    children: [
      { path: '/', element: <Home /> },
      { path: 'about', element: <About /> },
      { path: 'contact', element: <Contact /> },
      {
        path: 'posts',
        children: [
          { path: ':postId', element: <Post /> }
        ]
      }
    ]
  }
]);
Create the router instance using 'createBrowserRouter'. Define nested routes using the 'children' property.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);
Render the application with the RouterProvider at the top-level component to enable routing.