Skip to content
ClapelloNotes by Barath
ReactCh 07 · 3/6
Core4 min readUpdated

React / 36

React Router: first routes & links

TL;DR

Install React Router, map URLs to components with createBrowserRouter and RouterProvider, link with <Link>, and catch 404s with errorElement.

Install

npm install react-router

Map URLs to components

A router is a list of route objects. Each says "for this path, render this element":

main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter } from "react-router";
import { RouterProvider } from "react-router/dom";
import Home from "./pages/Home";
import About from "./pages/About";
import ErrorPage from "./pages/ErrorPage";
 
const router = createBrowserRouter([
  { path: "/", element: <Home />, errorElement: <ErrorPage /> },
  { path: "/about", element: <About /> },
]);
 
createRoot(document.getElementById("root")).render(
  <StrictMode>
    <RouterProvider router={router} />
  </StrictMode>,
);
  1. createBrowserRouter

    Takes your routes and creates a router that reads the real URL (/about). Create it once, outside any component.
  2. RouterProvider

    Renders whatever route matches the current URL, and re-renders when the URL changes.
  3. Your components

    Home and About are ordinary components. They don't know they're "pages".
Header.jsx
import { Link } from "react-router";
 
export default function Header() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

<Link> renders a real <a href="/about">, so right-click, Ctrl/Cmd-click (new tab) and screen readers all work. But a normal click is intercepted: the URL changes and React renders the new route, with no page load.

Plain <a> vs <Link>

Try it

the nav links are

localhost:5173/

Home

The cart count lives in React state in the header.

  1. Click a nav link to see what happens.
Add a few items to the cart, then click a nav link. With a plain <a>, the browser loads a new page and the cart empties. With <Link>, only the URL and the content change.

Don't

Plain <a> for your own pages

<a href="/about">About</a>

Full page load. The whole app restarts, state is lost, and everything re-downloads or re-runs.

Do

<Link> inside the app, <a> outside it

<Link to="/about">About</Link>
<a href="https://dummyjson.com/docs">API docs</a>

Link for routes in your app. A plain <a> is right for other websites.

Your own error and 404 page

Add errorElement to a route and it renders instead of that route's element when something goes wrong. Inside it, useRouteError() hands you what went wrong:

pages/ErrorPage.jsx
import { isRouteErrorResponse, Link, useRouteError } from "react-router";
 
export default function ErrorPage() {
  const error = useRouteError();
 
  return (
    <main>
      <h1>
        {isRouteErrorResponse(error)
          ? `${error.status} ${error.statusText}` // e.g. "404 Not Found"
          : "Something went wrong"}
      </h1>
      {error instanceof Error && <p>{error.message}</p>}
      <Link to="/">Back to home</Link>
    </main>
  );
}

It catches two kinds of trouble:

  • No route matched (like /oops). The router creates a 404 error response and sends it to the root route's errorElement, which is why the one on "/" above is your 404 page.
  • An error thrown while rendering a route. It goes to that route's errorElement, or the nearest parent's. With nested routes (next topic), one errorElement on the parent covers all of its children.

Without any errorElement, React Router shows its plain built-in "Unexpected Application Error!" screen.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.