Our To-Do app works, but it's one screen: App shows the login form or the task list depending on a token. The URL never changes. Refresh, and any filter you picked is gone. You can't send someone a link to one task. In this lesson we turn it into a real multi-page app with React Router 8:
| URL | Page | Who can see it |
|---|---|---|
| / | Redirects to /tasks | Everyone |
| /login | Log in or sign up | Everyone (logged-in users are sent on) |
| /tasks | The task list; ?filter=active or ?filter=done | Logged-in users |
| /tasks/5 | One task: details, mark done, delete | Logged-in users |
| anything else | "Page not found" | Everyone |
We built every file below, ran it against the To-Do API from the Node.js course, and clicked through each page in a browser, including logging out, refreshing a task page and visiting a URL that doesn't exist.
How client-side routing works
- 1
🖱️
You click a Link
React Router stops the browser's normal page load.
- 2
🔗
The URL changes
It updates the address bar and history, with no request to the server.
- 3
🧩
Routes are matched
It finds the route whose path fits the new URL.
- 4
⚡
React swaps the page
Only the parts that changed re-render. No white flash, no reload.
That's why it's called a single-page app (SPA): the server sends one index.html, and React Router fakes the rest of the pages in the browser.
Step 1: Install React Router
In the React app's folder (the backend from the last lesson should be running too):
$bun add react-router# npm users: npm install react-router
Step 2: List every page in one file
The heart of the app is a list of routes: which URL shows which component. We keep them all in router.tsx, so anyone can see the whole app's pages in one place:
import { createBrowserRouter, Navigate } from "react-router";
import { Layout } from "./components/Layout";
import { RequireAuth } from "./components/RequireAuth";
import { LoginPage } from "./pages/LoginPage";
import { TasksPage } from "./pages/TasksPage";
import { TaskPage } from "./pages/TaskPage";
import { NotFoundPage } from "./pages/NotFoundPage";
// Every page of the app, in one place: which URL shows which component.
export const router = createBrowserRouter([
{
path: "/",
Component: Layout, // the header around every page
children: [
{ index: true, element: <Navigate to="/tasks" replace /> }, // "/" → "/tasks"
{ path: "login", Component: LoginPage },
{
Component: RequireAuth, // pages below need a logged-in user
children: [
{ path: "tasks", Component: TasksPage },
{ path: "tasks/:id", Component: TaskPage },
],
},
{ path: "*", Component: NotFoundPage }, // any other URL
],
},
]);Read it from the outside in:
- Nested routes. Everything sits inside the
"/"route, whose component isLayout. Child paths are relative:"tasks"under"/"means/tasks. index: trueis the child shown at the parent's exact URL. Ours just redirects/to/tasks.- A route with no path (the one with
RequireAuth) groups pages under a shared component without adding anything to the URL. That's how both task pages get the login guard. :idis a URL parameter:tasks/:idmatches/tasks/5,/tasks/42, and so on."*"matches anything the other routes don't: our 404 page.
Then give the router to React in main.tsx. It replaces <App />, so delete App.tsx:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider } from "react-router/dom";
import { router } from "./router";
import "./index.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<RouterProvider router={router} />
</StrictMode>,
);Try the routes yourself. Type any URL, or switch “logged in” off:
Which page does this URL show?
Route matched
tasks/:id
Components rendered
What the page can read
const { id } = useParams();
// id === "42" (a string)
// useSearchParams(): nothing,
// this URL has no ?queryNested routes render inside each other: every page sits in Layout's <Outlet />, and the task pages also pass through RequireAuth.
Step 3: A layout with a menu (Outlet and NavLink)
Every page shares a header. Instead of copying it into each page, the parent route renders it once, and <Outlet /> marks where the current page goes:
import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router";
import { clearToken, getToken } from "../auth";
// The frame around every page. <Outlet /> is where the current page appears.
export function Layout() {
const navigate = useNavigate();
useLocation(); // re-render on every page change, so the header sees a fresh login or logout
const loggedIn = Boolean(getToken());
function logOut() {
clearToken();
navigate("/login");
}
return (
<div className="shell">
<header className="nav">
<Link to="/" className="brand">
✅ To-Do
</Link>
{loggedIn ? (
<nav>
<NavLink to="/tasks">My tasks</NavLink>
<button className="link" onClick={logOut}>
Log out
</button>
</nav>
) : (
<NavLink to="/login">Log in</NavLink>
)}
</header>
<Outlet />
</div>
);
}NavLinkaddsclass="active"when you're on its page (and on pages below it, like/tasks/5), so the menu shows where you are. A little CSS (.nav a.active) makes it green and bold.useNavigate()changes the page from code. Logging out clears the token, then goes to/login.
The token helpers moved out of App.tsx into their own small file:
// The login token lives in localStorage, so it survives a page reload.
export const getToken = () => localStorage.getItem("token");
export const saveToken = (token: string) => localStorage.setItem("token", token);
export const clearToken = () => localStorage.removeItem("token");Step 4: Protect pages with a route guard
Logged-out users shouldn't see /tasks. RequireAuth is a route component with no UI of its own: if there's a token it renders <Outlet /> (the page), otherwise it redirects:
import { Navigate, Outlet, useLocation } from "react-router";
import { getToken } from "../auth";
// A guard: shows the page only to logged-in users. Everyone else goes to /login,
// and we remember where they wanted to go so we can send them back after login.
export function RequireAuth() {
const location = useLocation();
if (!getToken()) {
return <Navigate to="/login" replace state={{ from: location.pathname + location.search }} />;
}
return <Outlet />;
}Notice state={{ from: … }}. If you open a link to /tasks/3 while logged out, the guard remembers that address and the login page sends you back to task 3 after you log in, not just to the list. We tested exactly this.
Step 5: The login page (redirect after login)
import { Navigate, useLocation, useNavigate } from "react-router";
import { LoginForm } from "../components/LoginForm";
import { getToken, saveToken } from "../auth";
export function LoginPage() {
const navigate = useNavigate();
const location = useLocation();
// Where the user was trying to go before RequireAuth sent them here (or /tasks).
const from = (location.state as { from?: string } | null)?.from ?? "/tasks";
// Already logged in? There's nothing to do here.
if (getToken()) return <Navigate to={from} replace />;
function handleLogin(token: string) {
saveToken(token);
navigate(from, { replace: true }); // replace: "Back" won't return to the login form
}
return (
<>
<title>Log in · To-Do</title>
<LoginForm onLogin={handleLogin} />
</>
);
}location.state?.fromis the address the guard saved. No saved address? Go to/tasks.navigate(from, { replace: true })replaces the login page in the history, so pressing Back after logging in doesn't show the login form again.<title>inside a component? Yes: React 19 moves it into the page's<head>, so each page gets its own browser-tab title. No extra library.
LoginForm itself doesn't change at all: it still calls onLogin(token). That's the payoff of small components with props.
Step 6: Put the filter in the URL (useSearchParams)
The All / Active / Done filter used to be useState, so a reload reset it. Search params keep it in the URL instead: /tasks?filter=done.
import { useSearchParams } from "react-router";
import type { Filter } from "../types";
import { useTasks } from "../hooks/useTasks";
import { TaskForm } from "../components/TaskForm";
import { TaskList } from "../components/TaskList";
import { FilterBar } from "../components/FilterBar";
const FILTERS: Filter[] = ["all", "active", "done"];
export function TasksPage() {
const { tasks, loading, error, addTask, toggleTask, deleteTask } = useTasks();
// The filter lives in the URL (?filter=done), so it survives a reload and can be shared.
const [searchParams, setSearchParams] = useSearchParams();
const fromUrl = searchParams.get("filter") as Filter;
const filter: Filter = FILTERS.includes(fromUrl) ? fromUrl : "all";
function changeFilter(next: Filter) {
setSearchParams(next === "all" ? {} : { filter: next });
}
const visibleTasks = tasks.filter((t) => (filter === "active" ? !t.done : filter === "done" ? t.done : true));
const left = tasks.filter((t) => !t.done).length;
return (
<main className="app">
<title>My tasks · To-Do</title>
<h1>My To-Do List</h1>
<TaskForm onAdd={addTask} />
<FilterBar filter={filter} onChange={changeFilter} />
{error && <p className="error">{error}</p>}
{loading ? <p className="empty">Loading your tasks…</p> : <TaskList tasks={visibleTasks} onToggle={toggleTask} onDelete={deleteTask} />}
<p className="count">
{left} {left === 1 ? "task" : "tasks"} left
</p>
</main>
);
}useSearchParams works like useState, but for the URL: read with searchParams.get("filter"), change with setSearchParams. Anything typed into a URL can be wrong, so we only accept the three known filters and fall back to “all”. Now reload, Back and shared links all keep the filter. The FilterBar component is unchanged.
| Keep it in… | When | Example |
|---|---|---|
| The URL (path) | Which thing you're looking at | /tasks/5 |
| The URL (search params) | How you're looking at it: filters, sort, page, search text | ?filter=done&page=2 |
| useState | Temporary UI that nobody would bookmark | Text typed in a box, an open menu |
Step 7: A page for one task (useParams)
First, the API helper needs a way to load a single task. One new line in api/client.ts:
getTask: (id: number) => request<Task>(`/api/tasks/${id}`),The API already returns createdAt, so we add it to the Task type to show when a task was added:
// What one task looks like. Every component that uses tasks imports this.
export type Task = {
id: number;
title: string;
done: boolean;
createdAt: string; // the API sends dates as text, e.g. "2026-11-20T16:30:00.000Z"
};
export type Filter = "all" | "active" | "done";Now the page itself:
import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router";
import type { Task } from "../types";
import { api } from "../api/client";
// One task on its own page: /tasks/5
export function TaskPage() {
const { id } = useParams(); // "5" from the URL /tasks/5 (always a string)
const navigate = useNavigate();
const [task, setTask] = useState<Task | null>(null);
const [error, setError] = useState("");
useEffect(() => {
let ignore = false; // if the id changes before the answer arrives, ignore the old answer
api
.getTask(Number(id))
.then((t) => !ignore && setTask(t))
.catch((err: Error) => !ignore && setError(err.message));
return () => {
ignore = true;
};
}, [id]);
async function toggle() {
if (!task) return;
setTask(await api.updateTask(task.id, { done: !task.done }));
}
async function remove() {
if (!task) return;
await api.deleteTask(task.id);
navigate("/tasks", { replace: true }); // the task is gone, so don't let "Back" return here
}
if (error) {
return (
<main className="app">
<title>Task not found · To-Do</title>
<h1>Couldn't open this task</h1>
<p className="error">{error}</p>
<Link to="/tasks">← All tasks</Link>
</main>
);
}
if (!task) return <main className="app"><p className="empty">Loading…</p></main>;
return (
<main className="app">
<title>{`${task.title} · To-Do`}</title>
<Link to="/tasks" className="back">
← All tasks
</Link>
<h1 className={task.done ? "done-title" : ""}>{task.title}</h1>
<p className="empty">
{task.done ? "✅ Done" : "⏳ Not done yet"} · added {new Date(task.createdAt).toLocaleDateString()}
</p>
<div className="actions">
<button onClick={toggle}>{task.done ? "Mark as not done" : "Mark as done"}</button>
<button className="danger" onClick={remove}>
Delete
</button>
</div>
</main>
);
}useParams()gives{ id: "3" }for/tasks/3. Params are always strings, henceNumber(id).[id]in the effect: when the URL changes to another task, the effect runs again. Theignoreflag throws away a slow, out-of-date answer, the same trick from the useEffect lesson.- Errors come from the API. We tried
/tasks/9999: the page shows “Couldn't open this task” with the API's message, “Task not found”. Someone else's task gives the same answer, because the API returns 404 for it. - After deleting,
navigate("/tasks", { replace: true })leaves the page and removes it from history, so Back can't return to a task that no longer exists.
Finally, make each task title in the list a link to its page. The checkbox moves out of the <label> so a click on the title opens the task instead of ticking it:
import { Link } from "react-router";
import type { Task } from "../types";
type Props = {
task: Task;
onToggle: (id: number) => void;
onDelete: (id: number) => void;
};
// One row in the list: a checkbox, the title (a link to the task's page), and a delete button.
export function TaskItem({ task, onToggle, onDelete }: Props) {
return (
<li className={task.done ? "task done" : "task"}>
<input type="checkbox" checked={task.done} onChange={() => onToggle(task.id)} aria-label={`Done: ${task.title}`} />
<Link to={`/tasks/${task.id}`}>{task.title}</Link>
<button onClick={() => onDelete(task.id)} aria-label={`Delete ${task.title}`}>
✕
</button>
</li>
);
}Step 8: A friendly 404 page
import { Link, useLocation } from "react-router";
// Shown for any URL that no route matches.
export function NotFoundPage() {
const { pathname } = useLocation();
return (
<main className="app">
<title>Page not found · To-Do</title>
<h1>Page not found</h1>
<p className="empty">
There's nothing at <code>{pathname}</code>.
</p>
<Link to="/">Go to my tasks</Link>
</main>
);
}The "*" route catches any URL nothing else matched. We opened /some/old/link and got “There's nothing at /some/old/link” with a link home, instead of a blank screen.
Step 9: The new styles
A few lines for the header, the active link and the task page, added to the end of index.css:
.nav { max-width: 480px; margin: 24px auto 0; padding: 0 8px; display: flex; justify-content: space-between; align-items: center; }
.nav nav { display: flex; gap: 12px; align-items: center; }
.nav a { color: #374151; text-decoration: none; }
.nav a.active { font-weight: 600; color: #059669; }
.nav .link { color: #374151; font-size: 16px; }
.brand { font-weight: 700; }
.app a { color: #059669; }
.back { display: inline-block; margin-bottom: 12px; }
.actions { display: flex; gap: 8px; margin-top: 16px; }
.danger { background: #dc2626; }
.done-title { text-decoration: line-through; color: #9ca3af; }One rule changes, because the title is now a link instead of a <span>: replace the old .task label and .task.done span rules with these.
.task { gap: 10px; }
.task a { flex: 1; color: inherit; text-decoration: none; }
.task a:hover { text-decoration: underline; }
.task.done a { text-decoration: line-through; color: #9ca3af; }What we tested
| We did this | What happened |
|---|---|
| Opened /tasks?filter=done while logged out | Sent to /login; after signing up, landed back on /tasks?filter=done |
| Clicked All | URL became /tasks and every task showed |
| Clicked a task title | Opened /tasks/3, tab title "Buy milk · To-Do", My tasks still highlighted |
| Marked it done, then refreshed | Still on /tasks/3, still done (it's saved in PostgreSQL) |
| Opened /tasks/9999 | "Couldn't open this task" with the API's "Task not found" |
| Opened /some/old/link | The 404 page |
| Deleted a task, then pressed Back | Stayed on the list, not the deleted task |
| Logged out, then pressed Back | Sent to /login again: the guard still works |
| Opened a link to /tasks/3 while logged out, then logged in | Landed on task 3 |
Before you deploy: the refresh 404
Everything works in bun run dev. But a SPA has only one real file, index.html. On a live site, when someone refreshes /tasks/3, the browser asks the server for a file at /tasks/3. We checked the built app: vite preview answered 200, but a plain static file server answered 404.
The fix is to tell your host: “for any path, send index.html”. React Router takes it from there.
| Host | What to add |
|---|---|
| Netlify | A file public/_redirects with the line: /* /index.html 200 |
| Vercel | vercel.json: { "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }] } |
| Cloudflare Pages | Nothing: it serves index.html automatically when your site has no 404.html |
| Your own Nginx | try_files $uri /index.html; |
The finished app
todo-app/src/ ├── main.tsx RouterProvider instead of <App /> ├── router.tsx every URL → component, in one place ├── auth.ts getToken · saveToken · clearToken ├── api/client.ts + getTask(id) ├── components/ │ ├── Layout.tsx header + <Outlet /> │ ├── RequireAuth.tsx the login guard │ ├── TaskItem.tsx the title is now a <Link> │ └── … TaskForm, TaskList, FilterBar, LoginForm (unchanged) ├── pages/ │ ├── LoginPage.tsx /login │ ├── TasksPage.tsx /tasks?filter=… │ ├── TaskPage.tsx /tasks/:id │ └── NotFoundPage.tsx everything else └── types.ts + createdAt
Cheat sheet
| Use | What it does | Where we used it |
|---|---|---|
| <Link to="/tasks"> | A link that changes the page without reloading | TaskItem, TaskPage, NotFoundPage |
| <NavLink> | A Link that gets class="active" on its own page | Layout's menu |
| <Outlet /> | Where a child route's page appears | Layout, RequireAuth |
| <Navigate to="…" /> | Redirects as soon as it renders | "/" → "/tasks", RequireAuth |
| useParams() | Reads :params from the URL, e.g. { id: "5" } | TaskPage |
| useSearchParams() | Reads and sets ?key=value, like useState for the URL | TasksPage |
| useNavigate() | Changes the page from code (after login, delete, logout) | LoginPage, TaskPage, Layout |
| useLocation() | The current URL and any state passed with it | RequireAuth, LoginPage |
Common mistakes
| Mistake | What goes wrong | Do this instead |
|---|---|---|
| Using <a href> for app pages | The whole page reloads and React state resets | <Link to> for pages inside the app |
| Importing from react-router-dom | "Cannot find module": v8 has no react-router-dom package | Import from "react-router" (RouterProvider from "react-router/dom") |
| Forgetting <Outlet /> | Child pages never appear | Every parent route component renders an <Outlet /> |
| Treating params as numbers | "5" === 5 is false | Number(id), and handle bad ids |
| Filters in useState | Lost on reload, can't be shared | useSearchParams |
| No SPA fallback on the host | Refreshing any page except / shows 404 | Rewrite every path to /index.html |
Key takeaways
- ✓Our To-Do app now has real pages: /login, /tasks, /tasks/:id and a 404, all with their own URLs.
- ✓All routes live in one router.tsx; a shared Layout renders the header and an <Outlet /> for each page.
- ✓RequireAuth redirects logged-out users and remembers where they were going.
- ✓URL params pick the thing (/tasks/5), search params hold the view (?filter=done).
- ✓Before deploying, add a SPA fallback so refreshing any page works.
Next: collect everything from this course into one checklist with React Best Practices.
Frequently asked questions
What is React Router?
React Router is the most used library for pages in a React app. It looks at the browser's URL and decides which component to show, gives you links that change the URL without reloading the page, and hooks like useParams and useNavigate to read and change the URL from code.
Should I install react-router or react-router-dom?
Install react-router. Since version 7 everything lives in that one package, and React Router 8 removed react-router-dom completely. Import components and hooks from "react-router", and RouterProvider from "react-router/dom".
What is the difference between Link and NavLink?
Both change the page without a reload. NavLink also knows when its URL is the current page and adds an "active" class (and aria-current="page"), so it's the one to use in menus and navigation bars.
Why do I get a 404 when I refresh a page after deploying?
On refresh the browser asks the server for that exact path, like /tasks/5, and a plain static host has no such file. Tell your host to send index.html for every path (a SPA fallback): a _redirects file on Netlify, a rewrite in vercel.json on Vercel. Cloudflare Pages does this on its own when your site has no 404.html.
Is a protected route secure?
It only hides pages in the browser, which anyone can change. The real protection is the API: every task request needs a valid token, and the server checks it. The route guard is there so logged-out users get a friendly login page instead of errors.
What about loaders, actions and framework mode?
React Router can also load data before a page shows (loaders), handle forms (actions), and, in framework mode, do server rendering and file-based routes. They're worth learning next. This lesson sticks to the core every mode shares: routes, links, params and navigation.
🧠 Quick check: React Router
1. Which hook reads the 42 from the URL /tasks/42 (route path "tasks/:id")?
2. Where should a filter like "done" live so it survives a reload and can be shared?
3. After a successful login, why navigate with { replace: true }?
4. Your app works locally, but refreshing /tasks/5 on the live site shows 404. Why?
Checking your access…