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.