Mapping URLs to Components

What this is. React itself has no router. React Router is the common choice, and it maps the current URL to which components render.

A route is a path and an element. A colon marks a parameter, and an asterisk catches everything unmatched.

Why a router rather than state. You could hold the current page in state and switch on it. It would work, and it would cost you every single thing a URL provides: the back button, bookmarking, opening in a new tab, sharing a link, and refreshing without losing your place.

The URL is application state that the browser stores for you and that people already know how to use. A router keeps your components in step with it.

Declaring routes

Routes

<Routes>
  <Route path="/"
    element={<Home />} />
  <Route path="/books/:id"
    element={<Book />} />
  <Route path="*"
    element={<NotFound />} />
</Routes>

Navigating

import {
  Link, useParams, useNavigate
} from 'react-router-dom';

<Link to="/books/42">Open</Link>

const { id } = useParams();
const navigate = useNavigate();
Compare → Use Link rather than a plain anchor, or the whole application reloads and you lose every advantage of a single page app. useNavigate is for moving after an action, such as a successful save.

✦ Route parameters are always strings

useParams gives you "42", not 42. Convert before doing arithmetic or comparing with ===. This is the same trap as reading a value out of an input, and it produces the same puzzling comparisons that are false when they look true.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: What Routing Breaks, and How to Fix It →
← Back