Using Dynamic Route Parameters in TanStack Router
Exemplify the use of dynamic route parameters for fetching and displaying a blog post based on its ID from the URL using TanStack Router.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack-router';
Import the required functions and components from tanstack-router.
function BlogPost({ id }) {
// Fetch blog post based on id
// Display the blog post content
return <div>Blog post content for {id}</div>;
}
Define a BlogPost component that takes an 'id' as a prop, fetches blog post data based on the ID, and renders the blog post content.
const router = createBrowserRouter([
{
path: '/blog/:id',
element: ({ params }) => <BlogPost id={params.id} />
}
]);
Create a router instance with a route for blog posts. Use dynamic route parameters to fetch and display a blog post based on its ID.
function App() {
return <RouterProvider router={router} />;
}
Define the main App component that utilizes RouterProvider to make the router available throughout the component hierarchy.