Blog>
Snippets

Dynamic Route Matching with TanStack Router

Show how to create dynamic routes using parameters, extracting those parameters within the component for data fetching.
import { createBrowserRouter, RouterProvider, Route } from '@tanstack/react-router';

// Define a dynamic route with parameters
const router = createBrowserRouter([
    {
        path: '/',
        element: <Home />, // Your Home component
    },
    {
        path: '/posts/:postId',
        element: <Post />, // Your Post component that will extract the postId
    },
]);

function App() {
    return <RouterProvider router={router} />;
}
This code snippet creates a router with a dynamic route for posts. The ':postId' part of the path represents a variable segment that will match any value, facilitating dynamic route matching.
import { useParams } from '@tanstack/react-router';

function Post() {
    const params = useParams();
    const postId = params.postId;

    useEffect(() => {
        // Fetch post data using the postId
        fetchPostById(postId).then(postData => {
            // Handle post data
        });
    }, [postId]);

    return (
        <div>
            {/* Render post details */}
        </div>
    );
}
This code snippet demonstrates how to extract URL parameters within the Post component using the useParams hook. The postId is then used to fetch the corresponding post data.