Dynamic Route Parameters in TanStack Router
Demonstrate how to handle dynamic routing in TanStack Router by creating a route that accepts parameters, such as user IDs, to fetch and display user-specific data.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
import UserProfile from './UserProfile';
First, import the necessary components from tanstack-router and the UserProfile component where the user data will be displayed.
const router = createBrowserRouter([
{
path: '/users/:userId',
element: async ({ params }) => {
const userId = params.userId;
const user = await fetchUserById(userId);
return <UserProfile user={user} />;
}
}
]);
Define a dynamic route that matches paths like '/users/:userId'. Use an asynchronous element function to fetch user-specific data based on the userId parameter, and then render the UserProfile component with the fetched data.
function App() {
return <RouterProvider router={router} />;
}
Define the App component that renders the RouterProvider with the created router. This sets up your React application to use TanStack Router for navigation.
async function fetchUserById(userId) {
// This is a mock function to fetch user data by ID
// Replace this with your actual data fetching logic
return fetch(`https://api.example.com/users/${userId}`).then(res => res.json());
}
Define an asynchronous function to fetch user data by ID. In a real application, this function would request data from your backend or API.