Creating Nested Routes with File-Based Structure
Show how to structure a React app to utilize file-based routing with TanStack Router, focusing on creating nested routes that reflect a directory-like structure in the filesystem.
// routes/index.jsx
import { createBrowserRouter, RouterProvider } from 'tanstack-router-react';
import App from '../App';
import HomePage from '../pages/HomePage';
import Dashboard from '../pages/dashboard/Dashboard';
import ReportPage from '../pages/dashboard/ReportPage';
import ProfilePage from '../pages/dashboard/ProfilePage';
// Define the routes using the file-based structure
const router = createBrowserRouter([
{
path: '/',
element: <App/>,
children: [
{ path: '/', element: <HomePage/> },
{ path: 'dashboard', element: <Dashboard/>,
children: [
{ path: 'reports', element: <ReportPage/> },
{ path: 'profile', element: <ProfilePage/> }
]
}
]
}
]);
// In the entry point file (e.g., index.js)
// Render the RouterProvider with the defined router
function App() {
return <RouterProvider router={router}/>
}
This code snippet demonstrates how to set up nested routes using TanStack Router with a file-based structure. Initially, it defines the routes in a file likely located under a 'routes' directory. Each route is represented as an object in an array, with nested routes defined under the 'children' property to mimic a directory-like structure. The top-level route loads the main 'App' component. Nested routes under '/dashboard' load respective components for 'ReportPage' and 'ProfilePage'. Finally, the 'RouterProvider' from TanStack is used to apply the routing configuration.