Nested Routing with Path Params Using TanStack Router
Provide an example on setting up nested routes that include dynamic path params, showcasing how components can render based on nested URL structures.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
Imports necessary components and functions from the TanStack Router package.
function Post({ postId }) {
return <div>Post ID: {postId}</div>;
}
Defines a Post component that will display a post based on a postId parameter.
function Comment({ commentId }) {
return <div>Comment ID: {commentId}</div>;
}
Defines a Comment component that displays a comment based on a commentId parameter.
const router = createBrowserRouter([
{
path: 'post/:postId',
element: <Post />, // Assumes Post component can extract postId from params
children: [
{
path: 'comment/:commentId',
element: <Comment /> // Assumes Comment component can extract commentId from params
}
]
}
]);
Creates a router instance defining a nested route structure. A parent route for posts includes a dynamic postId param. Each post route can have child routes for comments, which also include a dynamic commentId param.
function App() {
return <RouterProvider router={router} />;
}
Defines the main App component that utilizes the RouterProvider to enable routing defined by the TanStack Router instance.