Blog>
Snippets

Dynamic Route Matching

Show how to create dynamic routes using TanStack Router, focusing on path parameters for user profiles, e.g., '/users/:id', and accessing these parameters within the component.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
Imports required functions and components from 'react-router-dom' and the UserProfile component.
const router = createBrowserRouter([
  {
    path: '/users/:id',
    element: <UserProfile />
  }
]);
Creates a router object configuring a dynamic route for user profiles. The ':id' is a path parameter.
function App() {
  return <RouterProvider router={router} />;
}
Defines the main app component where the RouterProvider uses the defined router for navigation.
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams();
  // Use the id to fetch user data
  return <div>User profile page for {id}</div>;
}
The UserProfile component uses useParams hook to access the dynamic ':id' parameter and can use it to fetch and display the user's data.