# React Router DOM

> The industry standard library for client-side routing in React, using declarative components to match URLs to UI.

Subject: React | Lesson 37 of 48 | 6 min read
Interactive lesson: https://codewithanimation.in/react/react-router-dom
Previous: [Client-Side Routing](https://codewithanimation.in/react/client-side-routing.md) | Next: [Form State Management](https://codewithanimation.in/react/form-state-management.md)

## Declarative Routing

While you could build your own client-side router by listening to the `popstate` event, it gets incredibly complex when dealing with nested layouts, URL parameters, and query strings.

`react-router-dom` is the de facto standard library for routing in React. It allows you to declare your application's routes using standard JSX components.

The core idea is simple: You define a list of `<Route>` components. When the URL changes, the router looks through the list, finds the one that matches the URL, and renders its component.

## Dynamic Parameters and Catch-Alls

URLs are rarely static. You often need URLs like `/users/123` or `/products/shoes`.

React Router allows you to define dynamic segments using a colon, like `<Route path="/users/:id" />`.

When a user navigates to `/users/123`, React Router extracts `123` and makes it available to the rendered component via the `useParams()` hook.

You can also define a "catch-all" route using `path="*"` to render a 404 Not Found page if no other routes match.

## The Core Components

A standard React Router setup involves three main layers:

1. `<BrowserRouter>`: Wraps your entire app. It connects your app to the browser's URL history.

2. `<Routes>`: Acts as a switch. It looks at all its child `<Route>` components and picks the *best* match for the current URL.

3. `<Route>`: Defines a mapping between a URL path and a React component (e.g., `<Route path="/about" element={<About />} />`).

To navigate between pages, you use the `<Link to="/path">` component instead of standard `<a>` tags. `<Link>` intercepts the click and prevents the browser from reloading the page.

## Common mistake: Nested Routing Complexity

As apps grow, you often want persistent layouts (like a dashboard sidebar) where only the main content area changes.

React Router handles this elegantly with Nested Routes. A parent `<Route>` can render an `<Outlet />` component, which acts as a placeholder where matching child routes will be rendered.

## Tip: Programmatic Navigation

Sometimes you need to change the page after an action, like successfully submitting a login form.

You can use the `useNavigate()` hook to navigate programmatically: `const navigate = useNavigate();` then `navigate('/dashboard');`.

## Try it: The Router Engine

Click the links in the mock browser to see how React Router's `<Routes>` component matches the URL to a specific `<Route>` declaration, extracting dynamic parameters along the way.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/react-router-dom

## Check yourself

### Question 1

Why should you use `<Link to="/about">` instead of `<a href="/about">` when using React Router?

- A. Because <a> tags do not support CSS styling in React.
- B. Because `<Link>` prevents the browser's default behavior of doing a full page reload, allowing the SPA to update instantly.
- C. Because `<Link>` automatically prefetches the data for the next page.

Correct answer: B

A standard `<a>` tag will always trigger a full page request to the server. `<Link>` intercepts the click and updates the History API instead.

### Question 2

If your route is defined as `<Route path="/users/:userId" />`, how do you access the `userId` in the component?

- A. Using the `useParams()` hook.
- B. It is automatically passed as a prop: `props.userId`.
- C. Using `window.location.search`.

Correct answer: A

React Router parses the dynamic segments of the URL and exposes them via the `useParams()` hook as an object (e.g., `{ userId: "123" }`).

### Question 3

How do you define a '404 Not Found' route in React Router v6?

- A. Using `<Route path="404" />`
- B. By placing a `<Route path="*" />` at the end of your routes list.
- C. Using the `<NotFound>` component.

Correct answer: B

The asterisk `*` acts as a wildcard/catch-all that matches any URL. React Router will use it if no more specific routes match.

## Remember this

- `<BrowserRouter>` connects your app to the browser's URL.
- `<Routes>` evaluates child routes and picks the best match.
- `<Route>` maps a specific `path` to a component `element`.
- Dynamic segments (like `:id`) are accessed via `useParams()`.
- Always use `<Link>` instead of `<a>` for internal navigation.
