Dynamic Route Parameter Retrieval
Showcase retrieving parameters from a dynamic segment of a URL in a nested route, using hooks provided by TanStack Router to access route parameters within components.
import { createBrowserRouter, RouterProvider, useRouteLoaderData } from 'react-tanstack-router-dom';
First, import necessary hooks and components from 'react-tanstack-router-dom'.
const router = createBrowserRouter([
{
path: '/',
element: <App />, // Assume App is your root component
children: [
{
path: 'project/:projectId',
element: <ProjectDetail />, // Component to render for this path
loader: async ({ params }) => {
// Fetching project data based on projectId
const response = await fetch(`/api/projects/${params.projectId}`);
return response.json();
}
}
]
}
]);
Define routes using 'createBrowserRouter'. Use ':projectId' as a dynamic segment in the path which you can retrieve in the loader function using 'params'.
function ProjectDetail() {
// Using 'useRouteLoaderData' to access the loader's result
const projectData = useRouteLoaderData();
// Now 'projectData' contains the fetched data based on 'projectId'
return (
<div><h1>{projectData.name}</h1><p>{projectData.description}</p></div>
);
}
In the component, use 'useRouteLoaderData' hook to access the fetched data based on the dynamic route parameter.
function App() {
return (
<RouterProvider router={router} />
);
}
Wrap your application with 'RouterProvider' to enable routing as defined.