← React / TypeScript

React / TypeScript · 20 / 24

React web routing and deep links

Open a record directly by URL and handle unknown IDs.

  • Large
  • Advanced
  • 90 min

Prerequisites: First React app: JSX, props and state, Forms, lists and effects

In this tutorial
  1. Understand the state model
  2. Start the project
  3. Verify the contract with a test
  4. Observe failures and boundaries
  5. Implement the exercise
  6. Verify the solution
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

Node.js 22.23 or newer with npm. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. Component and Chromium tests verify direct detail URLs, browser reload, back navigation and unknown IDs. Vite supplies the application-route fallback. A different production server must configure this separately.

A route describes addressable state. Its path contains a stable ID rather than a copied record. Direct navigation and reload resolve the record from the same source again. A missing record is different from an unknown route.

Package contents and individual files

01Understand the state model

The URL carries the resource ID. A detail view reads that ID and finds the matching record. This makes the address shareable. An unknown ID gets its own state rather than silently showing the first record.

src/App.tsx · typescriptOpen file
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useParams,
} from "react-router-dom";
const vehicles: Record<string, string> = {
  car: "Family car",
  bike: "Motorbike",
};
function Detail() {
  const { id } = useParams();
  return (
    <main>
      <h1>{(id && vehicles[id]) || "Vehicle not found"}</h1>
      <Link to="/">All vehicles</Link>
    </main>
  );
}
export function Screens() {
  return (
    <Routes>
      <Route
        path="/"
        element={
          <main>
            <h1>Vehicles</h1>
            <Link to="/vehicles/car">Family car</Link>
          </main>
        }
      />
      <Route path="/vehicles/:id" element={<Detail />} />
      <Route path="*" element={<h1>Page not found</h1>} />
    </Routes>
  );
}
export default function App() {
  return (
    <BrowserRouter>
      <Screens />
    </BrowserRouter>
  );
}

02Start the project

Install the pinned dependencies and run npm run dev. Data consists of synthetic learning values. Open the local address and trigger the action yourself.

package.json · jsonOpen file
{
  "name": "appfabrik-learning",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "tsc --noEmit && vite build",
    "test": "vitest run src"
  },
  "dependencies": {
    "react": "19.2.3",
    "react-dom": "19.2.3",
    "react-router-dom": "7.18.4",
    "@tanstack/react-query": "5.104.5"
  },
  "devDependencies": {
    "vite": "8.1.5",
    "typescript": "6.0.3",
    "@types/react": "19.2.14",
    "@types/react-dom": "19.2.3",
    "@types/node": "22.19.15",
    "vitest": "4.1.10",
    "@testing-library/react": "16.3.2",
    "@testing-library/user-event": "14.6.1",
    "jsdom": "29.1.1",
    "@playwright/test": "1.64.1"
  }
}

03Verify the contract with a test

Start the test at a detail URL and also check an unknown ID. A real browser reload requires the web server to send index.html for application routes. The router does not configure that server.

src/App.test.tsx · typescriptOpen file
// @vitest-environment jsdom
import { test, expect, afterEach } from "vitest";
import { render, screen, cleanup } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { Screens } from "./App";
afterEach(cleanup);
test("direct URL resolves the record and back navigation", async () => {
  render(
    <MemoryRouter initialEntries={["/vehicles/car"]}>
      <Screens />
    </MemoryRouter>,
  );
  expect(screen.getByRole("heading").textContent).toBe("Family car");
  await userEvent.click(screen.getByRole("link", { name: "All vehicles" }));
  expect(screen.getByRole("heading").textContent).toBe("Vehicles");
});
test("unknown record is explicit", () => {
  render(
    <MemoryRouter initialEntries={["/vehicles/missing"]}>
      <Screens />
    </MemoryRouter>,
  );
  expect(screen.getByRole("heading").textContent).toBe("Vehicle not found");
});

Run / check

npm install
npm test
npm run build
Expected result

Start the test at a detail URL and also check an unknown ID. A real browser reload requires the web server to send index.html for application routes. The router does not configure that server.

04Observe failures and boundaries

Change the expected output and observe a failed test. A TypeScript build protects type contracts while a browser test protects interactions. The two checks serve different purposes.

05Implement the exercise

Verify an unknown route outside /vehicles.

06Verify the solution

The additional test opens /missing and expects Page not found. A production host additionally needs an SPA fallback routing direct requests for frontend paths to the entry document. Vite supplies this only for the learning server. Copy the solution files to the corresponding locations in the learning project and run tests and build again.

Expected result

Tests and type checking pass. The observed result matches the learning goal.

Your exercise

Verify an unknown route outside /vehicles.

Show the solution and explanation

The additional test opens /missing and expects Page not found. A production host additionally needs an SPA fallback routing direct requests for frontend paths to the entry document. Vite supplies this only for the learning server.

solution/App.test.tsx · typescriptOpen file
// @vitest-environment jsdom
import { test, expect, afterEach } from "vitest";
import { render, screen, cleanup } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { Screens } from "./App";
afterEach(cleanup);
test("direct URL resolves the record and back navigation", async () => {
  render(
    <MemoryRouter initialEntries={["/vehicles/car"]}>
      <Screens />
    </MemoryRouter>,
  );
  expect(screen.getByRole("heading").textContent).toBe("Family car");
  await userEvent.click(screen.getByRole("link", { name: "All vehicles" }));
  expect(screen.getByRole("heading").textContent).toBe("Vehicles");
});
test("unknown record is explicit", () => {
  render(
    <MemoryRouter initialEntries={["/vehicles/missing"]}>
      <Screens />
    </MemoryRouter>,
  );
  expect(screen.getByRole("heading").textContent).toBe("Vehicle not found");
});

test("unknown route", () => {
  render(
    <MemoryRouter initialEntries={["/missing"]}>
      <Screens />
    </MemoryRouter>,
  );
  expect(screen.getByRole("heading").textContent).toBe("Page not found");
});

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.