Blog>
Snippets

Dynamic Route Matching with Type Safety

Demonstrate configuring dynamic routes using TanStack Router, focusing on maintaining type safety for route parameters and fetched data.
import { createBrowserRouter, RouterProvider } from 'tanstack-router-dom';
import UserProfile from './UserProfile';
import NotFound from './NotFound';
First, import necessary components from TanStack Router, including `createBrowserRouter` and `RouterProvider`, as well as the user profile component and a not found component for unmatched routes.
const router = createBrowserRouter([
  {
    path: 'user/:userId',
    element: ({ params }) => <UserProfile id={params.userId} />,
    loader: async ({ params }) => {
      const userData = await fetch(`https://api.example.com/users/${params.userId}`).then(res => res.json());
      return { userData };
    }
  },
  { path: '*', element: <NotFound /> }
]);
Define the router with dynamic route matching. The user profile route captures the `userId` parameter, fetches user data, and passes it to the `UserProfile` component. A catch-all route directs to the `NotFound` component for unmatched paths.
function App() {
  return <RouterProvider router={router} />;
}
Finally, create the App component that renders the `RouterProvider` with the configured routes.