Blog>
Snippets

Defining Dynamic Routes with TanStack Router

Show how to define dynamic routes using TanStack Router, including parsing parameters from the URL to load specific content based on the route.
import { createBrowserRouter, RouterProvider, Route } from '@tanstack/react-router';
import { fetchPost } from './api';
import PostComponent from './components/PostComponent';
Imports necessary components and functions from TanStack Router, the API, and a PostComponent that will render the content based on the route parameter.
const router = createBrowserRouter([
  {
    path: '/',
    element: <HomeComponent />,
    errorElement: <NotFoundComponent />
  },
  {
    path: 'posts/:postId',
    element: <PostComponent />, 
    loader: async ({ params }) => {
      return fetchPost(params.postId);
    }
  }
]);
Defines the router configuration, including a dynamic route for individual posts using a parameter 'postId'. The 'loader' function fetches specific content based on this parameter.
function App() {
  return <RouterProvider router={router} />;
}
Defines the App component that incorporates the RouterProvider with the configured router to enable routing in the application.