React / 36
React Router: first routes & links
Install React Router, map URLs to components with createBrowserRouter and RouterProvider, link with <Link>, and catch 404s with errorElement.
Install
npm install react-routerMap URLs to components
A router is a list of route objects. Each says "for this path, render this element":
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>,
);createBrowserRouter
Takes your routes and creates a router that reads the real URL (/about). Create it once, outside any component.RouterProvider
Renders whatever route matches the current URL, and re-renders when the URL changes.Your components
HomeandAboutare ordinary components. They don't know they're "pages".
Link between pages
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 itthe nav links are
Home
The cart count lives in React state in the header.
- Click a nav link to see what happens.
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:
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'serrorElement, 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), oneerrorElementon 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.
