React Router
Nested routes, dynamic segments, route guards, loaders, and navigation patterns.
Overview
React Router enables client-side routing in React applications with a declarative API.
Key Concepts
- Routes — Define URL-to-component mappings
- Dynamic Segments — Capture URL parameters with
:idsyntax - Nested Routes — Create layouts that wrap child routes
- Route Guards — Protect routes with authentication checks
- Loaders — Pre-fetch data before rendering a route
Code Examples
import { BrowserRouter, Routes, Route, useParams, Navigate } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="users" element={<Users />} />
<Route path="users/:id" element={<UserProfile />} />
<Route path="dashboard" element={
<ProtectedRoute><Dashboard /></ProtectedRoute>
} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
);
}
function UserProfile() {
const { id } = useParams();
return <h1>User {id}</h1>;
}
Practice
Create a multi-page app with nested layouts and protected dashboard route.