Basic Route Setup with TanStack Router
Demonstrate setting up TanStack Router in a JavaScript project, defining basic public and authenticated routes.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router-dom';
import Home from './components/Home';
import Dashboard from './components/Dashboard';
import Login from './components/Login';
Imports the necessary components from the TanStack router package and the application's page components.
const router = createBrowserRouter([
{ path: '/', element: <Home />, index: true },
{ path: 'login', element: <Login /> },
{ path: 'dashboard', element: <Dashboard />, loader: async () => {
// Assume isAuthenticated checks user's auth status
if (!isAuthenticated()) {
return { redirect: '/login' };
}
}
}
]);
Creates a router instance with public routes for Home and Login, and an authenticated route for Dashboard which redirects to Login if not authenticated.
function App() {
return <RouterProvider router={router} />;
}
Defines the App component that utilizes the RouterProvider to enable routing within the application.