Initializing TanStack Router with Dynamic Path Params
Show how to set up TanStack Router in a JavaScript project and define a route with dynamic path parameters, explaining how to capture and use these parameters within a component.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import UserProfile from './components/UserProfile';
Imports necessary functions and components from TanStack Router and the user profile component.
const router = createBrowserRouter([
{
path: 'user/:userId',
element: <UserProfile />,
loader: async ({ params }) => {
// Simulate fetching user data based on the userID
const userData = await fetchUserData(params.userId);
return { user: userData };
}
}
]);
Creates a browser router with a dynamic route. The route uses a path parameter (userId) that is passed to the loader function to fetch user data asynchronously.
function App() {
return <RouterProvider router={router} />;
}
Defines the main App component that renders the router using RouterProvider from TanStack Router.