Client-Side Routing with React Router
50 minReact Router is the standard library for routing in React.
It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
Key components include `BrowserRouter`, `Routes`, `Route`, and `Link`.
React Router v6 introduced significant changes including the new `Routes` and `Route` API, nested routes, and improved data loading patterns.
Route parameters allow dynamic segments in URLs, accessible via the `useParams` hook. Query strings can be accessed with `useSearchParams`.
Navigation can be programmatic using the `useNavigate` hook, or declarative using the `Link` and `NavLink` components.
Key Concepts
- React Router enables client-side routing in single-page applications.
- BrowserRouter provides routing context, Routes defines route configuration.
- Route parameters enable dynamic URL segments.
- Link and NavLink provide declarative navigation.
- useNavigate enables programmatic navigation.
Learning Objectives
Master
- Setting up React Router in an application
- Creating routes and route parameters
- Implementing navigation with Link and useNavigate
- Handling nested routes and route protection
Develop
- Understanding single-page application architecture
- Designing URL structures for applications
- Implementing navigation patterns and user flows
Tips
- Use NavLink instead of Link when you need active state styling.
- Extract route configuration into a separate file for better organization.
- Use route parameters for dynamic content (e.g., /users/:id).
- Implement route protection for authenticated routes.
Common Pitfalls
- Forgetting to wrap the app with BrowserRouter.
- Using anchor tags (<a>) instead of Link, causing full page reloads.
- Not handling 404 cases with a catch-all route.
- Creating routes that are too deeply nested, making URLs hard to manage.
Summary
- React Router enables client-side routing in React applications.
- Routes define URL-to-component mappings.
- Link and useNavigate provide navigation capabilities.
- Route parameters enable dynamic routing.
Exercise
Set up a basic router with a Home and About page.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<h1>Home</h1>} />
<Route path="/about" element={<h1>About</h1>} />
</Routes>
</BrowserRouter>
);
}
Exercise Tips
- Add a 404 route with path='*' for unmatched routes.
- Use NavLink for active link styling.
- Extract routes into a separate configuration object.
- Add route parameters for dynamic pages.