Blog>
Snippets

Implementing Dynamic Routes with TanStack Router

Provide an example of how to set up dynamic routes using TanStack Router, demonstrating how to handle route parameters and integrate them into component rendering.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
import React from 'react';
import UserProfile from './UserProfile'; // Assuming this is a component that will use the route param

// Define the routes
const router = createBrowserRouter([
    {
        // Define dynamic route with :userId
        path: 'users/:userId',
        element: <UserProfile />,
        loader: async ({ params }) => {
            // Fetch data based on userId from params
            const userData = await fetchUserById(params.userId);
            return { userData };
        }
    }
]);

// Component that uses the Router
function App() {
    return <RouterProvider router={router} />;
}
This code first imports necessary functions and components from the 'tanstack-router' package and a user profile component. It then defines a router with createBrowserRouter, including a dynamic route for user profiles identified by a user ID. This route uses an asynchronous loader function to fetch and return user data based on the ID from the route parameters. Finally, it presents the RouterProvider component that uses the defined router, allowing the app to render the appropriate component based on the current route.