React Router is the standard routing library for single-page React applications. 1. Install: npm install react-router (v7; the react-router-dom package re-exports it for compatibility). 2. Define routes (data router style, recommended) import { createBrowserRouter, RouterProvider } from 'react-router'; const router = createBrowserRouter([ { path: '/', element: <RootLayout />, // shared layout with navigation errorElement: <ErrorPage />, // route-level error handling children: [ { index: true, element: <Home /> }, { path: 'products', element: <ProductList /> }, { path: 'products/:id', element: <ProductDetail />, loader: productLoader }, { path: 'admin', element: <RequireAuth role="admin"><AdminPage /></RequireAuth> }, { path: 'reports', lazy: () => import('./routes/reports') }, // code splitting { path: '*', element: <NotFound /> }, ], }, ]); createRoot(document.getElementById('root')!).render(<RouterProvider router={router} />); The declarative alternative uses <BrowserRouter> with <Routes> and <Route> elements. 3. Layouts render child routes with <Outlet /> function RootLayout() { return ( <> <nav> <NavLink to="/" end>Home</NavLink> <NavLink to="/products">Products</NavLink> </nav> <main><Outlet /></main> </> ); } NavLink adds an active class automatically. 4. Navigation and parameters - Links: <Link to={`/products/${p.id}`}>. - Programmatic: const navigate = useNavigate(); navigate('/orders', { replace: true }); - URL parameters: const { id } = useParams(); - Query strings: const [params, setParams] = useSearchParams(); params.get('page'); 5. Data loading - Loaders fetch data before the route renders (useLoaderData), and actions handle form submissions, with built-in pending states (useNavigation). 6. Protected routes A wrapper component checks authentication and renders <Navigate to="/login" replace state={{ from: location }} /> when needed. Remember that route protection is only for UX; the API must still authorise every request. 7. Deployment detail The server must return index.html for unknown paths (SPA fallback) so deep links and page refreshes work, unless you use React Router's framework mode with server rendering. Alternatives: TanStack Router (type-safe routing), or file-based routing in frameworks such as Next.js.
Ravindra Wadile · · 0 likes