React Router is the standard library for routing in React applications. It enables navigation among different components, changes the browser URL, and keeps the UI in sync with the URL. This lesson covers the essentials: what React Router is, its core concepts, and best practices for using it in your React projects.
What is React Router?
React Router is a collection of navigational components that compose declaratively with your application. It allows you to build single-page applications (SPAs) with navigation without full page reloads. React Router keeps your UI and URL in sync, enabling dynamic, client-side navigation.
Core Concepts
- Declarative Routing: Define routes as part of your component tree, making navigation predictable and maintainable.
- Dynamic Routing: Routes can be generated and rendered based on your app's state or data.
- Nested Routes: Organize your app with parent and child routes for complex layouts.
- URL Parameters: Pass data through the URL for dynamic content.
- Fallback Routes: Handle unknown URLs with a custom 404 page.
Best Practices for Using React Router
- Keep Routes Organized: Use a dedicated file or component to define your routes, especially for larger apps.
- Use
<Link>
and <NavLink>
for Navigation: Avoid using <a>
tags for internal navigation to prevent full page reloads.
- Leverage Nested Routes: Structure your routes to reflect your app's layout and hierarchy.
- Handle 404s Gracefully: Always include a fallback route to catch undefined paths.
- Use Route Parameters for Dynamic Content: Pass IDs or slugs in the URL for detail pages.
Example: Defining and Using Routes
Below is an example of how to set up basic and fallback routes, and how to use navigation links.
1import React from "react";
2import { BrowserRouter, Routes, Route, Link, NavLink } from "react-router-dom";
3
4function Home() {
5 return <h2>Home Page</h2>;
6}
7
8function About() {
9 return <h2>About Page</h2>;
10}
11
12function NotFound() {
13 return <h2>404 - Page Not Found</h2>;
14}
15
16function Navbar() {
17 return (
18 <nav>
19 <Link to="/">Home</Link>
20 <NavLink to="/about" activeclassname="active">About</NavLink>
21 </nav>
22 );
23}
24
25function App() {
26 return (
27 <BrowserRouter>
28 <Navbar />
29 <Routes>
30 <Route path="/" element={<Home />} />
31 <Route path="/about" element={<About />} />
32 <Route path="*" element={<NotFound />} />
33 </Routes>
34 </BrowserRouter>
35 );
36}
37
38export default App;
- Use
<Link>
and <NavLink>
for navigation between pages.
- The
path="*"
route matches any undefined path and displays a custom Not Found message.
Programmatic Navigation
Programmatic navigation lets you change routes in response to events, not just user clicks on links. This is useful for redirecting users after actions like form submissions or authentication.
What is Programmatic Navigation?
Programmatic navigation allows you to control routing in your app using code, typically with the useNavigate
hook from React Router.
Best Practices
- Use programmatic navigation for redirects after user actions (e.g., login, logout, form submit).
- Avoid overusing redirects; prefer declarative navigation when possible.
- Keep navigation logic clear and easy to follow.
Example: Redirect After Login
Here's how to use useNavigate
to redirect after a form submission:
1import { useNavigate } from "react-router-dom";
2
3function LoginForm() {
4 const navigate = useNavigate();
5
6 function handleLogin(event) {
7 event.preventDefault();
8 // ...login logic
9 navigate("/dashboard");
10 }
11
12 return (
13 <form onSubmit={handleLogin}>
14 <button type="submit">Login</button>
15 </form>
16 );
17}