Build a Responsive React Catalog with React Router
Introduction
This is lesson 2 of chapter 8 (domain capstone). Lesson 1 produced a brief, user stories, a data model, a route table, and a slice plan. The first slices form a responsive React catalog with a shared layout, a workshop detail route, and a URL filter. By the end of the lesson the Harbor Workshops application runs, navigates, and looks like a product, even though booking is not wired yet.
These OnLevelUp exercises apply the Meta capstone skills of designing a responsive interface and composing multiple React views. Revisit React Router navigation and URL state before wiring the catalog and detail routes.
Learning objectives
By the end of this lesson you can:
- Create a Vite React project and organize the folders from your plan.
- Write a semantic page skeleton with landmarks, a skip link, and Open Graph metadata.
- Build a responsive catalog with CSS grid and design tokens.
- Configure client-side routes, nested layouts, route parameters, and a not-found route.
- Store the level filter in the URL query string and read it back.
- Build reusable components with clear props and without duplicated markup.
- Handle empty and unknown-id states.
1. Create the skeleton
npm create vite@latest harbor-workshops -- --template react
cd harbor-workshops
npm install
npm install react-router@8
npm run devUse Node.js 24 for the example toolchain. Keep the lockfile so another learner can reproduce the dependency versions with npm ci. These snippets use React Router 8 in Declarative Mode and import the routing APIs from react-router. Run the commands in a new practice project. Vite setup (opens in a new tab) · React Router installation (opens in a new tab)
The HTML shell and metadata
The Vite starter serves an index.html shell for this single-page app. Set its language, viewport, title, description, and link preview metadata.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Harbor Workshops: hands-on classes in town</title>
<meta name="description" content="Browse and book pottery, bike repair and baking workshops." />
<meta property="og:title" content="Harbor Workshops" />
<meta property="og:description" content="Browse and book hands-on community workshops." />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://workshops.example/" />
<meta property="og:image" content="https://workshops.example/og-image.png" />
<meta property="og:image:alt" content="A pottery wheel with a clay bowl" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>The language attribute helps assistive technology select pronunciation. The viewport setting lets phone layouts use the device width. Replace the example Open Graph URLs with your public deployment URL and an existing preview image before sharing. A client-only page served from one HTML shell usually exposes its default metadata to preview bots. Publish route-specific HTML when distinct previews are needed. Open Graph protocol (opens in a new tab)
Set a descriptive browser title for each view. Pair the title with a focus policy, since updating document.title alone may leave focus behind after a client-side navigation.
// src/hooks/useDocumentTitle.js
import { useEffect } from 'react';
export function useDocumentTitle(title) {
useEffect(() => {
if (title) document.title = `${title} | Harbor Workshops`;
}, [title]);
}2. The layout component and landmarks
A layout component renders what is shared by many routes: header, navigation, footer, and a slot for page content. Semantic elements create landmarks that assistive technology can jump between.
// src/components/Layout.jsx
import { useEffect, useRef } from 'react';
import { NavLink, Outlet, useLocation } from 'react-router';
export default function Layout() {
const { pathname } = useLocation();
const previousPath = useRef(pathname);
const main = useRef(null);
useEffect(() => {
if (previousPath.current !== pathname) {
previousPath.current = pathname;
main.current?.focus();
}
}, [pathname]);
return (
<>
<a className="skip-link" href="#main">Skip to main content</a>
<header className="site-header">
<p className="brand">Harbor Workshops</p>
<nav aria-label="Main">
<ul className="nav-list">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/workshops" end>Workshops</NavLink></li>
</ul>
</nav>
</header>
<main id="main" ref={main} tabIndex={-1}>
<Outlet />
</main>
<footer className="site-footer">
<p>12 Quay Street. Open Tuesday to Saturday.</p>
</footer>
</>
);
}Important details:
- Exactly one
<main>per page, and it is where<Outlet />renders the current route. NavLinkaddsaria-current="page"and anactiveclass to the matching link automatically. React Router treats/as a special case and matches Home only at the root.endon/workshopsgives the catalog link exact matching, so a detail route does not label the catalog as the current page. NavLink matching (opens in a new tab)- Skip link. It lets keyboard users bypass the navigation. Make it the first focusable element and reveal it on focus. The effect moves focus to
mainafter path changes and leaves it on the filter control when only the query changes. Check the behavior with a keyboard and screen reader. aria-label="Main"distinguishes this navigation from any other<nav>(for example, a footer nav).
Add these skip link and focus styles to src/styles/global.css together with the tokens from lesson 1. Add --color-focus: #0b5cad and --color-border: #74808c to :root.
.skip-link {
position: absolute;
left: var(--space-2);
top: var(--space-1);
transform: translateY(calc(-100% - var(--space-1)));
background: var(--color-primary);
color: #fff;
padding: var(--space-1) var(--space-2);
z-index: 10;
}
.skip-link:focus { transform: none; }
body {
margin: 0;
background: var(--color-bg);
color: var(--color-text);
font: 1rem/1.5 var(--font-body);
}
.site-header, main, .site-footer { padding: var(--space-2); }
.nav-list { display: flex; flex-wrap: wrap; gap: var(--space-2); padding: 0; list-style: none; }
.nav-list a.active { font-weight: 700; text-decoration-thickness: 0.15em; }
:focus-visible {
outline: 3px solid var(--color-focus);
outline-offset: 2px;
}Check that the focus outline stays visible against the surrounding colors, including near the edge of a container.
3. Routing
Set up the router in main.jsx and the routes in App.jsx:
// src/main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router';
import App from './App.jsx';
import './styles/global.css';
createRoot(document.getElementById('root')).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
);// src/App.jsx
import { Routes, Route } from 'react-router';
import Layout from './components/Layout.jsx';
import Home from './pages/Home.jsx';
import Catalog from './pages/Catalog.jsx';
import WorkshopDetail from './pages/WorkshopDetail.jsx';
import NotFound from './pages/NotFound.jsx';
export default function App() {
return (
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="workshops" element={<Catalog />} />
<Route path="workshops/:id" element={<WorkshopDetail />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
);
}A route without a path that has an element is a layout route: it wraps its children without adding a URL segment. The index route renders at the parent URL. The * route catches everything else.
BrowserRouter uses the History API for paths such as /workshops/w-101. Configure the host to serve index.html for app routes on direct visits and reloads while still serving static assets normally. The React catch-all supplies an on-screen not-found view. HTTP status codes come from the host. Record the rewrite rule in the README and check a deployed deep link. Vite static deployment (opens in a new tab)
Create the two small route components used by App.jsx. The shared not-found component provides a title for missing routes and workshops.
// src/pages/Home.jsx
import { Link } from 'react-router';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
export default function Home() {
useDocumentTitle('Home');
return (
<>
<h1>Harbor Workshops</h1>
<p>Try pottery, bike repair, or another hands-on class.</p>
<Link to="/workshops">Browse workshops</Link>
</>
);
}// src/pages/NotFound.jsx
import { Link } from 'react-router';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
export default function NotFound({ message = 'This page could not be found.' }) {
useDocumentTitle('Page not found');
return (
<>
<h1>Page not found</h1>
<p>{message}</p>
<Link to="/workshops">Browse workshops</Link>
</>
);
}The first version of the detail page shows availability from the fixtures. Lesson 3 replaces it with the shared booking calculation and enables the booking link.
Links and buttons by purpose
Use Link and NavLink for in-app navigation. They render anchors and handle same-tab navigation through the router. A regular anchor to an app route reloads the document and resets its in-memory state. Use buttons for actions such as changing the filter.
4. The catalog with CSS grid
The card component
// src/components/WorkshopCard.jsx
import { Link } from 'react-router';
import { seatsLeft } from '../api/workshops';
import { formatPrice, formatDate } from '../lib/format';
export default function WorkshopCard({ workshop }) {
const left = seatsLeft(workshop);
return (
<article className="card" aria-labelledby={`workshop-${workshop.id}`}>
<h2 id={`workshop-${workshop.id}`} className="card-title">
<Link to={`/workshops/${workshop.id}`}>{workshop.title}</Link>
</h2>
<p className="meta">
<span>{workshop.level}</span> ·{' '}
<time dateTime={workshop.startsAt}>{formatDate(workshop.startsAt)}</time>
</p>
<p>{workshop.summary}</p>
<p className="price">{formatPrice(workshop.priceCents)}</p>
<p className={left === 0 ? 'seats seats-out' : 'seats'}>
{left === 0 ? 'Fully booked' : `${left} seats left`}
</p>
</article>
);
}Design decisions: an <article> is a self-contained item; the heading is the link, so the whole title is one focus stop rather than a vague "Read more" link; <time> gives machines the date; status is written in words, not only color.
The formatting helpers are pure and testable:
// src/lib/format.js
export const formatPrice = (cents) =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(cents / 100);
export const formatDate = (iso) =>
new Intl.DateTimeFormat('en-US', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'America/New_York',
}).format(new Date(iso));The fixture amounts are in USD cents. Change the locale to adapt number and date formatting. A different currency code changes the label and formatting, so currency conversion needs a separate exchange-rate rule. The example displays workshop times in the venue's New York time zone.
The responsive grid
.card-grid {
display: grid;
gap: var(--space-2);
grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
list-style: none;
padding: 0;
}
.card {
background: #fff;
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: var(--space-2);
overflow-wrap: anywhere;
}auto-fill creates the tracks that fit in the container. Each minimum is 16rem or the available width, whichever is smaller. Let long content wrap as well. Use the lesson on responsive layouts with CSS Grid and Flexbox to choose where layout rules or breakpoints belong.
The catalog page and the URL filter
// src/pages/Catalog.jsx
import { useSearchParams } from 'react-router';
import { listWorkshops } from '../api/workshops';
import WorkshopCard from '../components/WorkshopCard.jsx';
import LevelFilter from '../components/LevelFilter.jsx';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
const LEVELS = ['beginner', 'intermediate', 'advanced'];
export default function Catalog() {
useDocumentTitle('Workshops');
const [params, setParams] = useSearchParams();
const raw = params.get('level');
const level = LEVELS.includes(raw) ? raw : ''; // validate untrusted input
const items = listWorkshops({ level });
function changeLevel(next) {
const updated = new URLSearchParams(params);
if (next) updated.set('level', next);
else updated.delete('level');
setParams(updated);
}
return (
<>
<h1>Workshops</h1>
<LevelFilter value={level} levels={LEVELS} onChange={changeLevel} />
<p role="status">
{items.length === 1 ? '1 workshop shown' : `${items.length} workshops shown`}
</p>
{items.length === 0 ? (
<p>No workshops match this level yet. Try another level.</p>
) : (
<ul className="card-grid" role="list">
{items.map((w) => (
<li key={w.id}><WorkshopCard workshop={w} /></li>
))}
</ul>
)}
</>
);
}Points worth studying:
- The URL is the state. There is no
useStatefor the filter. The query string?level=beginneris the single source of truth. Reloads and shared links keep it. Each filter update here pushes a history entry so Back can restore the prior choice. - Validate input from the URL. Anyone can type
?level=<script>. CheckingLEVELSmakes unknown values fall back to "All". Keep the other query parameters when changing the filter. role="status"turns the count into a polite live region, so assistive technology can announce changes after filtering.- List semantics. Each workshop card sits inside an
<li>. Check that the list is still announced after styling. Safari can drop list semantics whenlist-style: noneis applied outside navigation, so this example setsrole="list"on the catalog list.
// src/components/LevelFilter.jsx
export default function LevelFilter({ value, levels, onChange }) {
return (
<div role="group" aria-labelledby="level-label" className="filter">
<span id="level-label">Level</span>
<button type="button" aria-pressed={value === ''} onClick={() => onChange('')}>All</button>
{levels.map((l) => (
<button key={l} type="button" aria-pressed={value === l} onClick={() => onChange(l)}>
{l}
</button>
))}
</div>
);
}aria-pressed conveys the toggle state to assistive technology; style [aria-pressed="true"] so the state is visible by more than color (for example a thicker border).
5. The detail page
// src/pages/WorkshopDetail.jsx
import { Link, useParams } from 'react-router';
import { getWorkshop, seatsLeft } from '../api/workshops';
import NotFound from './NotFound.jsx';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { formatDate, formatPrice } from '../lib/format';
export default function WorkshopDetail() {
const { id } = useParams();
const workshop = getWorkshop(id);
useDocumentTitle(workshop?.title);
if (!workshop) return <NotFound message="We could not find that workshop." />;
const left = seatsLeft(workshop);
return (
<article>
<p><Link to="/workshops">Back to workshops</Link></p>
<h1>{workshop.title}</h1>
<p>{workshop.summary}</p>
<dl className="facts">
<dt>Instructor</dt><dd>{workshop.instructor}</dd>
<dt>Starts</dt><dd>{formatDate(workshop.startsAt)}</dd>
<dt>Duration</dt><dd>{workshop.durationMinutes} minutes</dd>
<dt>Price</dt><dd>{formatPrice(workshop.priceCents)}</dd>
<dt>Seats left</dt><dd>{left}</dd>
</dl>
{left > 0 ? (
<p>Booking opens in the next project slice.</p>
) : (
<p>This workshop is fully booked.</p>
)}
</article>
);
}The description list (dl, dt, dd) is the right element for label-value facts. Returning the not-found component for an unknown id keeps the same URL, and a good practice is to also set the HTTP status on the server in a real deployment (a client-only app cannot, so say so in the README).
Comparison: routing and layout choices
| Question | Option A | Option B | Prefer |
|---|---|---|---|
| Shared header and footer | Repeat in every page | Layout route with <Outlet /> |
B: one place to change |
| Filter state | useState in Catalog |
URL query parameter | B: shareable, reload-safe |
| In-app navigation | <a href> |
<Link> / <NavLink> |
B: no full reload |
| Responsive columns | Many media queries | auto-fill with minmax |
B: fewer rules |
| Card link | "Read more" on each card | Title as link | B: meaningful link text |
| Status | Color only | Text plus color | B: accessible |
Worked example: add a "sort by date" control
Problem. Visitors want the catalog sorted by start date ascending or descending, and the choice must survive a reload.
Step 1: choose where state lives. Like the level filter, sorting is shareable and affects what the page shows, so it belongs in the URL: ?sort=date-desc.
Step 2: validate. Allow only date-asc and date-desc; otherwise default to date-asc.
const SORTS = ['date-asc', 'date-desc'];
const rawSort = params.get('sort');
const sort = SORTS.includes(rawSort) ? rawSort : 'date-asc';Step 3: compute, do not store. Sort a copy during render.
const sorted = [...items].sort((a, b) =>
sort === 'date-asc'
? Date.parse(a.startsAt) - Date.parse(b.startsAt)
: Date.parse(b.startsAt) - Date.parse(a.startsAt),
);These fixtures contain valid timestamps with explicit offsets. Comparing their parsed times sorts them chronologically even when offsets differ. Copy the array before sorting to avoid mutating the data module.
Step 4: update params without losing the level. Build a new URLSearchParams from the existing one.
function update(key, value) {
const next = new URLSearchParams(params);
if (value) next.set(key, value); else next.delete(key);
setParams(next);
}Why not the alternatives? Keeping sort in useState would reset on reload and break shared links. Sorting in an effect and storing the result in state creates derived state that can go out of sync with the filter. Calling items.sort(...) directly would mutate shared data and cause hard-to-find bugs in other screens.
Common pitfalls and study tips
- Unexpected section highlighting.
/workshopsmatches detail URLs by default. Setendwhen the link should indicate the catalog page only. - Using
indexaskey. Useworkshop.id; stable keys keep component state attached to the right item. - Mutating arrays with
sortorreverse. Copy first. - Nested interactive elements. Do not put a button inside a link or a link inside a button.
outline: nonewith no replacement. Keyboard users lose focus visibility.- Heading levels chosen for size. Use one
<h1>per page and descending levels; style with CSS. - Trusting the query string. Always validate values read from the URL.
- Refresh returns 404 in production. Configure the host to fall back to
index.html.
Study tip. If a question offers "store the filter in component state" versus "store it in the URL," choose the URL when the requirement mentions sharing, bookmarking, reload, or the back button. If it asks which element should wrap the unique page content, the answer is <main>.
Mini case study: the bike-shop catalog
A bike shop front end lists 40 bikes. Its first version uses div for every part, a useState for the selected category, and <a href="/bike/3"> for each card, with index as the key. Users report that filters reset on refresh, Back cannot restore the earlier category, screen reader users have trouble finding the main content, and sorting the list scrambles the typed "quantity" inputs of other cards.
Task. Diagnose each symptom and give the fix.
Solution.
- Filters reset on refresh. The category is in memory only. Move it to the query string with
useSearchParamsand validate it. - Back cannot restore the earlier category. The filter lives only in component state. Update the query with a history push for each filter change. Ordinary anchors do create document history entries. Use
Linkto avoid reloading the app when opening a detail route. - Main content is difficult to locate. The page has no landmarks or headings. Use
header,nav,main,footer, a singleh1, and arole="status"result count. - Typed quantities scramble after sorting. Keys are array indexes, so React reuses component state by position. Use the bike id as the key.
Each fix applies a principle from this lesson, and none requires a new library.
Key terms
- Landmark: a semantic region (
header,nav,main,footer) that assistive technology can navigate. - Skip link: a link that lets keyboard users jump to main content.
- Layout route: a route that wraps child routes with shared UI via
<Outlet />. - Route parameter: a URL segment such as
:id, read withuseParams. - Query string: the
?key=valuepart of a URL, read withuseSearchParams. - Open Graph: meta tags that define link previews.
- CSS grid
auto-fill: creates as many columns as fit. - Live region: an element whose changes are announced, such as
role="status".
Summary checklist
- The project runs with Vite and has the folder structure from the plan.
-
index.htmlsetslang, viewport, title, description, and Open Graph tags. - The layout provides a skip link, header, nav, one
main, and footer. - Routes include index, catalog, detail with
:id, and a not-found route. - The catalog is a responsive grid with meaningful link text and text status.
- The level filter is stored in a validated URL parameter.
- Unknown ids and empty results show helpful messages.
- Focus is always visible, and the page works with the keyboard.
Sources and further reading
- React Router Declarative Mode installation (opens in a new tab)
- React Router NavLink matching (opens in a new tab)
- React Router useSearchParams (opens in a new tab)
- Vite static deployment (opens in a new tab)
- MDN list styling and accessibility (opens in a new tab)
- MDN, HTML elements reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element (opens in a new tab)
- MDN, CSS grid layout: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout (opens in a new tab)
- The Open Graph protocol: https://ogp.me/ (opens in a new tab)
- W3C WAI, landmark regions: https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions/ (opens in a new tab)
- React documentation: https://react.dev/learn (opens in a new tab)
