Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

Routing With React Router: One Page, Many Addresses

A task app with five routes: how the router picks the best match, why Link makes zero requests while a plain a tag downloads the app again, the Outlet slot, the useParams string trap (TS2367), useNavigate after a save, a not-found page and the 404 on refresh.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain why a single-page app loads one index.html for every address
  • Write a route table and predict which route matches a URL
  • Use Link, Outlet, useParams and useNavigate, and avoid the string id bug
  • Add a not-found route and make the host serve index.html on refresh

Before you start

  • React components, props and state
  • React 19 form actions (for the save example)

On a normal website, clicking a link sends the browser to the server for a new page, and everything starts again. A single-page app works differently. The browser asks for / once, gets one HTML page plus the JavaScript, and from then on the address bar changes without any new page being requested. Only part of the screen is redrawn.

React Router is what maps those addresses to components. This article follows a small task app with five routes, using the outputs from the lecture's scripts and a real Chrome session.

One HTML file for every page

The app has one index.html with an empty <div id="root"> and a script tag for main.tsx. npm run build writes exactly one HTML file, one JavaScript file and one CSS file:

dist/index.html  0.40 kB │ gzip:  0.27 kB
dist/assets/index-CKRgU76b.css  0.76 kB │ gzip:  0.39 kB
dist/assets/index-BkWeoiI8.js  315.91 kB │ gzip: 99.56 kB

So /, /tasks and /tasks/2 all get the same page, and JavaScript draws the right screen into the root.

The route table

import type { RouteObject } from 'react-router'
import Layout from './Layout'
import Tasks from './Tasks'
import TaskDetail from './TaskDetail'
import NewTask from './NewTask'
import NotFound from './NotFound'

// The route table: a URL path -> the component.
// Children are drawn inside Layout's <Outlet />.
export const routes: RouteObject[] = [
  {
    path: '/',
    element: <Layout />,
    children: [
      { index: true, element: <h3>Welcome</h3> },
      { path: 'tasks', element: <Tasks /> },
      { path: 'tasks/:id', element: <TaskDetail /> },
      { path: 'tasks/new', element: <NewTask /> },
      { path: '*', element: <NotFound /> },
    ],
  },
]

Routes are plain data: a path and the element to show. The parent at / draws Layout for every path, and its children are drawn inside Layout's Outlet. Two special paths: :id is a placeholder that matches any one part of the URL, and * matches anything no other route matches.

How the router matches a URL

/          -> index <h3>            {}
/tasks     -> tasks Tasks           {}
/tasks/2   -> tasks/:id TaskDetail  {"id":"2"}
/tasks/new -> tasks/new NewTask     {}
/oops      -> * NotFound            {"*":"oops"}

/tasks/new fits two routes: tasks/:id (with id "new") and tasks/new word for word. The first one in the list doesn't win; the more exact one does. A fixed word beats :id, and :id beats *. Note that the id in {"id":"2"} is text.

The router reads the address bar

import { createRoot } from 'react-dom/client'
import { createBrowserRouter } from 'react-router'
import { RouterProvider } from 'react-router/dom'
import { routes } from './routes'
import './index.css'

// Reads the address bar and keeps it in sync
const router = createBrowserRouter(routes)

createRoot(document.getElementById('root')!).render(
  <RouterProvider router={router} />,
)

createBrowserRouter takes the routes and reads the address bar. RouterProvider draws the match and keeps listening: a new URL means a new match and a new render.

Link and the Outlet

import { Link, Outlet } from 'react-router'

// The shared frame. Only the Outlet changes.
export default function Layout() {
  return (
    <>
      <nav className="nav">
        <b>Team tasks</b>
        <Link to="/">Home</Link>
        <Link to="/tasks">Tasks</Link>
        <Link to="/tasks/new">New task</Link>
      </nav>
      <main className="page">
        <Outlet />
      </main>
    </>
  )
}
The Outlet is the slot the child route fills nav: Team tasks · Home · Tasks · New task never rebuilt <Outlet /> / → Welcome /tasks → Tasks (three links) /tasks/2 → Email Jack, Owner: Noah
Nested routes share the parent's layout. Only the slot changes.

A Link renders a normal <a href="/tasks">. On a click it calls preventDefault(), so the browser doesn't go to the server, then writes the new URL with history.pushState. The router sees it, matches, and redraws the Outlet:

/ -> Outlet: Welcome
click "Tasks": default prevented = true
  history.pushState("/tasks")
/tasks -> Outlet: Tasks
click "Email Jack": default prevented = true
  history.pushState("/tasks/2")
/tasks/2 -> Outlet: Email Jack | Owner: Noah
nav is the same element: true

The last line matters: the nav is the same element before and after. Only the Outlet changed.

Link or a plain <a>?

The lecture compares both in a real Chrome window, putting a small note on window before each click to see whether the page survives:

StepRequestsWindow note
Open /1 document, 21 in total(not set yet)
Link to /tasks0kept
Plain <a href> to /tasks/21 document, 20 in totalgone

A plain <a> works, but every click downloads and starts the whole app again and loses everything in memory. Inside your app, use Link. For another site, use a plain <a href>.

Links built from data

import { Link } from 'react-router'
import { tasks } from './data'

export default function Tasks() {
  return (
    <div className="card">
      <h3>Tasks</h3>
      <ul>
        {tasks.map((t) => (
          <li key={t.id}>
            <Link to={`/tasks/${t.id}`}>
              {t.title}
            </Link>
          </li>
        ))}
      </ul>
    </div>
  )
}

A template string builds each address from the task id: id 2 gives /tasks/2.

useParams: the URL as data

import { Link, useParams } from 'react-router'
import { tasks } from './data'

export default function TaskDetail() {
  const { id } = useParams() // always a string
  const task = tasks.find((t) => t.id === Number(id))

  if (!task) return <p>No task with id {id}</p>
  return (
    <div className="card">
      <h3>{task.title}</h3>
      <p>Owner: {task.owner}</p>
      <Link to="/tasks">Back to tasks</Link>
    </div>
  )
}
useParams(): {"id":"2"}
typeof params.id: string
Number(params.id): 2
/tasks/2 -> Outlet: Email Jack | Owner: Noah
/tasks/9 -> Outlet: No task with id 9

useParams() gives the :id part as a string, text from the URL. The ids in data.ts are numbers, so line 6 converts with Number(id) before comparing. An id that doesn't exist, like 9, shows a message instead of crashing.

A number is not a string

Forget Number and write t.id === id. A number is never === a string, so find gives undefined, and the page says "No task with id 2" for a task that exists:

/tasks/2 -> Outlet: No task with id 2
/tasks/9 -> Outlet: No task with id 9

TypeScript catches it before it runs:

src/TaskDetail.tsx(6,34): error TS2367: This comparison appears to be unintentional because the types 'number' and 'string | undefined' have no overlap.

useNavigate after an action

import { useNavigate } from 'react-router'
import { addTask } from './data'

export default function NewTask() {
  const navigate = useNavigate()

  function save(form: FormData) {
    const task = addTask(String(form.get('title')))
    // done: send the user to the new task's page
    navigate(`/tasks/${task.id}`)
  }

  return (
    <form className="card" action={save}>
      <h3>New task</h3>
      <input name="title" placeholder="Title" />
      <button>Save</button>
    </form>
  )
}

Sometimes you move the user from code, for example after saving a form. The form action adds the task (id 4) and calls navigate, which does the same pushState a Link does:

/tasks/new -> Outlet: New task
click "Save"
  history.pushState("/tasks/4")
/tasks/4 -> Outlet: Call Olivia | Owner: Olivia

The not-found route

import { Link, useLocation } from 'react-router'

// '*' matches any URL no other route matches
export default function NotFound() {
  const { pathname } = useLocation()
  return (
    <div className="card">
      <h3>Page not found</h3>
      <p>Nothing lives at {pathname}</p>
      <Link to="/">Go home</Link>
    </div>
  )
}
/oops -> Outlet: Page not found | Nothing lives at /oops
nav links: Home | Tasks | New task

path: '*' catches every unknown URL, and because it is a child of Layout, the nav is still there. useLocation gives the current path for the message. A typo shows a page, not a blank screen.

A refresh on a deep URL

Press F5 on /tasks/2 and the browser really does ask the server for /tasks/2. There is no such file. The lecture asks two servers for both paths:

http://localhost:5173
  GET /        -> 200 index.html
  GET /tasks/2 -> 200 index.html
http://localhost:8000
  GET /        -> 200 index.html
  GET /tasks/2 -> 404 not the app

The Vite dev server (port 5173) knows this is a single-page app and sends index.html; the app starts, the router reads /tasks/2 and draws Email Jack again. A plain file server (port 8000) answers 404. When you host the app, the host must answer every app path with index.html.

Recap

PieceWhat it does
index.htmlOne page for every address; JavaScript draws into root
Route tablePath to element; the most exact match wins, * only as a last resort
LinkpreventDefault + pushState: no request, state kept
OutletThe slot in the layout that the child route fills
useParamsURL params as strings; convert with Number
useNavigateMove the user from code, for example after a save
HostingServe index.html for every app path

Try it yourself: add a route tasks/:id/edit with its own component, and work out which route /tasks/2/edit matches before you click. The next step for this app is real data from a server, covered in server state with TanStack Query.

Keep going in React · 17 of 59

Previous
React Props and Composition: Data Down, Calls Up, Children in the Slot
Next post
React Component Tests With Vitest and Testing Library: Test What the User Sees
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx

Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.

How a Web Page Works: HTML Tags, Elements and Attributes

A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.

Semantic HTML: header, nav, main, aside and footer as Page Landmarks

The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.

On this page

  • One HTML file for every page
  • The route table
  • How the router matches a URL
  • The router reads the address bar
  • Link and the Outlet
  • Link or a plain <a>?
  • Links built from data
  • useParams: the URL as data
  • A number is not a string
  • useNavigate after an action
  • The not-found route
  • A refresh on a deep URL
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.