Blog>
Snippets

Implementing Dynamic Routing with TanStack Router

Demonstrates how to use TanStack Router to implement dynamic routing, including extracting parameters from the URL to render specific components or data.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack/react-router';
Imports necessary components from the TanStack Router library.
function UserDetails({ params }) {
  // Extract the userID from the URL parameters
  const { userID } = params;
  return <div>User ID: {userID}</div>;
}
Defines a React component that uses URL parameters to display information.
function App() {
  // Create a router instance
  const router = createBrowserRouter([
    {
      path: '/',
      element: <h2>Home Page</h2>,
    },
    {
      path: 'user/:userID',
      element: <UserDetails />,
      loader: async ({ params }) => {
        // Optional: Load data based on the userID
      }
    }
  ]);

  return <RouterProvider router={router} />;
}
Sets up dynamic routing for the application with a route that includes a parameter.