How to Build a Frontend Picture Book
CSS · paint & layout HTML · the structure JavaScript · power three languages, three jobs
PLATE 0 — Structure, style, behaviour. Keep them separate and everything is easier.
A picture book for grown-ups · with code

How to Build a Frontend

Nine spreads, from a blank HTML file to a deployed, accessible, fast React app that talks to an API.

Say it like a pro

"Semantic HTML, mobile-first CSS, components with a single source of state, data fetched with loading and error states, tested, accessible, and built by Vite."

Use the tabs or the ← → keys to turn pages.

<header> · <nav> <main> <article> <h1> <p> … <section> <form> … <aside> <footer> meaning, not just boxes: screen readers and search engines use it
PLATE 1 — Use the element that says what the content is.
Chapter 1 · HTML

Structure first

HTML describes what things are. Browsers, assistive tech and search engines all read it, so choose elements for meaning.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Tasks</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header><h1>My Tasks</h1><nav><a href="/">Home</a></nav></header>
  <main>
    <form id="add">
      <label for="title">New task</label>
      <input id="title" name="title" required maxlength="200">
      <button type="submit">Add</button>
    </form>
    <ul id="list"></ul>
  </main>
  <script src="app.js" defer></script>
</body></html>
<label for>
every input needs one; it also enlarges the tap target
<button>
for actions · <a> for navigation. Never a clickable <div>.
alt text
<img src alt="Tom's red bike">; empty alt="" if decorative
Say it like a pro

"Landmarks, real buttons and links, labelled inputs. Accessibility starts in the markup."

margin border padding content box-sizing: border-box Flexbox: one direction Grid: rows and columns Pick the tool flexbox: a row or column of things (navbar, button group, centering) grid: a page or card layout in two dimensions
PLATE 2 — Every element is a box. Flexbox and grid arrange the boxes.
Chapter 2 · CSS

Style, spacing, and layout

:root {
  --bg: #fff; --text: #1a1a1a; --brand: #2f5bea;
  --space: 1rem; --radius: 8px;
}
@media (prefers-color-scheme: dark) {
  :root { --bg: #111; --text: #eee; --brand: #7b9bff; }
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font: 1rem/1.5 system-ui, sans-serif; background: var(--bg); color: var(--text); }

.card { padding: var(--space); border: 1px solid #8884; border-radius: var(--radius); }
.row  { display: flex; gap: var(--space); align-items: center; justify-content: space-between; }
.grid { display: grid; gap: var(--space);
        grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); }   /* responsive, no media query */
button:focus-visible { outline: 3px solid var(--brand); outline-offset: 2px; }
rem
relative to root font size; scales with user settings
custom props
--brand: one place to change a theme
specificity
class selectors, not IDs or !important
Say it like a pro

"Design tokens as custom properties, flex for one dimension, grid for two."

phone1 column tablet2 columns desktopsidebar + 2 cols Mobile first write the phone layout as the default, then add min-width rules breakpoints follow where your content breaks, not device names
PLATE 3 — One codebase, every screen size.
Chapter 3 · Responsive design

Start with the phone, grow from there

/* default: phone, one column */
.layout { display: grid; gap: 1rem; padding: 1rem; }

@media (min-width: 40rem) {      /* ~640px */
  .layout { grid-template-columns: 1fr 1fr; }
}
@media (min-width: 64rem) {      /* ~1024px */
  .layout { grid-template-columns: 16rem 1fr 1fr; }
}

img { max-width: 100%; height: auto; }
.container { width: min(100% - 2rem, 70rem); margin-inline: auto; }
h1 { font-size: clamp(1.75rem, 4vw + 1rem, 3rem); }   /* fluid type */
  • Always include the viewport meta tag, or phones show a shrunken desktop page.
  • Tap targets at least ~44×44 px, with space between them.
  • Test in browser DevTools device mode, then on a real phone.
  • Respect prefers-reduced-motion and prefers-color-scheme.
Say it like a pro

"Mobile-first, fluid type, content-driven breakpoints, and no horizontal scroll at any width."

document header main form ul The event loop of a UI user click handler new state re-render events: click, input, submit, keydown · state: the data the UI is a picture of
PLATE 4 — The browser turns HTML into a tree (the DOM). JavaScript edits the tree in response to events.
Chapter 4 · JavaScript & the DOM

Make the page respond

// app.js: plain JavaScript, no framework
const form = document.querySelector('#add');
const list = document.querySelector('#list');
let tasks = [];

function render() {
  list.replaceChildren(...tasks.map(t => {
    const li = document.createElement('li');
    li.textContent = t.title;                 // textContent, not innerHTML (XSS!)
    return li;
  }));
}

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const title = new FormData(form).get('title').trim();
  if (!title) return;
  tasks.push({ id: crypto.randomUUID(), title });
  form.reset();
  render();
});

render();
state → UI
change data, then redraw from it, rather than patching the DOM by hand
innerHTML
with user text it runs scripts. Prefer textContent.
async
fetch returns a promise: await it, handle failure
Say it like a pro

"UI is a function of state: update the data, re-render, and never inject untrusted HTML."

App · state TaskForm TaskList TaskItem TaskItem props ↓ callbacks ↑ Component = a function that returns UI same inputs → same output · small, reusable, one job each lift state up to the nearest common parent
PLATE 5 — Data flows down as props. Events flow up as callbacks.
Chapter 5 · Components & state (React)

Build the UI from small pieces

$ npm create vite@latest my-app -- --template react
$ cd my-app && npm install && npm run dev
// App.jsx
import { useState } from 'react';

export default function App() {
  const [tasks, setTasks] = useState([]);
  const add = (title) => setTasks(t => [...t, { id: crypto.randomUUID(), title, done: false }]);
  const toggle = (id) => setTasks(t => t.map(x => x.id === id ? { ...x, done: !x.done } : x));
  return (
    <main>
      <h1>My Tasks</h1>
      <TaskForm onAdd={add} />
      <TaskList tasks={tasks} onToggle={toggle} />
    </main>
  );
}

function TaskForm({ onAdd }) {
  const [title, setTitle] = useState('');
  return (
    <form onSubmit={e => { e.preventDefault(); if (title.trim()) { onAdd(title.trim()); setTitle(''); } }}>
      <label>New task <input value={title} onChange={e => setTitle(e.target.value)} /></label>
      <button>Add</button>
    </form>
  );
}

function TaskList({ tasks, onToggle }) {
  return <ul>{tasks.map(t => (
    <li key={t.id}><label><input type="checkbox" checked={t.done} onChange={() => onToggle(t.id)} /> {t.title}</label></li>
  ))}</ul>;
}
immutable
make new arrays/objects; never mutate state directly
key
a stable ID per list item, not the array index
Say it like a pro

"Small components, state lifted to the owner, immutable updates, stable keys."

idle loading success error retry Every screen that loads data has four views skeleton empty state error + retry the data design all four · never leave the user staring at a blank page cancel stale requests when inputs change (AbortController) never trust a response shape: handle non-2xx and bad JSON
PLATE 6 — The network is slow and sometimes broken. Plan for it.
Chapter 6 · Fetching data

Loading, error, empty, success

// api.js
const BASE = import.meta.env.VITE_API_URL;       // set in .env, e.g. http://localhost:3000/api/v1
export async function api(path, opts = {}) {
  const res = await fetch(BASE + path, {
    ...opts,
    headers: { 'Content-Type': 'application/json',
               Authorization: `Bearer ${localStorage.getItem('token') ?? ''}`, ...opts.headers },
    body: opts.body && JSON.stringify(opts.body),
  });
  if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error?.message ?? res.statusText);
  return res.status === 204 ? null : res.json();
}
// useTasks.js: a custom hook
import { useEffect, useState } from 'react';
export function useTasks() {
  const [state, setState] = useState({ status: 'loading', data: [], error: null });
  useEffect(() => {
    const ctrl = new AbortController();
    api('/tasks', { signal: ctrl.signal })
      .then(data => setState({ status: 'ok', data, error: null }))
      .catch(e => e.name !== 'AbortError' && setState({ status: 'error', data: [], error: e.message }));
    return () => ctrl.abort();
  }, []);
  return state;
}
// in the component:  loading → <Skeleton/> · error → retry · data.length===0 → <Empty/> · else the list
CORS
the browser blocks cross-origin calls unless the API allows your origin
libraries
TanStack Query adds caching, retries and refetching for free
tokens
an httpOnly cookie is safer than localStorage against XSS
Say it like a pro

"One API wrapper, a status for every fetch, abort stale requests, and a designed empty and error state."

https://app.example.com/tasks/42 / → Home /tasks → List /tasks/:id swap components; the page never reloads Email ama@ ⚠ Enter a full email, like name@example.com Sign up error text is next to the field, linked with aria-describedby
PLATE 7 — The URL picks the screen. Forms explain exactly what went wrong.
Chapter 7 · Routing & forms

Multiple pages, one app

$ npm install react-router-dom
// main.jsx
import { createBrowserRouter, RouterProvider, Link, useParams } from 'react-router-dom';

const router = createBrowserRouter([
  { path: '/',          element: <Home /> },
  { path: '/tasks',     element: <TaskList /> },
  { path: '/tasks/:id', element: <TaskDetail /> },
  { path: '*',          element: <NotFound /> },
]);
// <RouterProvider router={router} />     link with <Link to="/tasks">, not <a href>

function TaskDetail() { const { id } = useParams(); /* fetch task `id` */ }
// An accessible, validated form field
function Field({ label, error, ...props }) {
  const id = useId();
  return (<div>
    <label htmlFor={id}>{label}</label>
    <input id={id} aria-invalid={!!error} aria-describedby={error ? id + '-err' : undefined} {...props} />
    {error && <p id={id + '-err'} role="alert">{error}</p>}
  </div>);
}
history fallback
host must serve index.html for unknown paths, or deep links 404
validation
validate in the browser for speed, and again on the server for safety
Say it like a pro

"Client-side routing with a 404 route, and accessible inline validation on every form."

Accessible (a11y) ✔ works with keyboard only ✔ visible focus ring ✔ contrast ≥ 4.5 : 1 ✔ labels, alt text, headings ✔ not colour alone ✔ respects reduced motion Fast (Core Web Vitals) LCP ≤ 2.5 s main content shown INP ≤ 200 ms taps feel instant CLS ≤ 0.1 nothing jumps images sized · code split cache static assets Measure, don't guess Lighthouse in Chrome DevTools · axe DevTools extension tab through your page with the mouse unplugged throttle the network to "Slow 4G" and reload
PLATE 8 — A frontend that's slow or unusable for some people isn't finished.
Chapter 8 · Accessibility & performance

Build it for everyone, and keep it quick

  1. Semantics: real buttons, links, headings in order, landmarks.
  2. Keyboard: everything reachable and operable; never remove focus outlines without a replacement.
  3. Contrast and size: text readable on every theme; respect user font size with rem.
  4. Images: width/height set, loading="lazy", modern formats (WebP/AVIF).
  5. JavaScript: split by route, drop unused libraries, defer what isn't needed at first paint.
// code-split a route so it loads only when visited
import { lazy, Suspense } from 'react';
const Settings = lazy(() => import('./Settings'));
// <Suspense fallback={<Skeleton/>}><Settings/></Suspense>
$ npm run build && npm run preview      # measure the production build, not dev
$ npx lighthouse http://localhost:4173 --view
Say it like a pro

"Keyboard and screen-reader tested, Core Web Vitals in the green, and routes code-split."

src/ Vite buildbundle+minify dist/hashed files CDN CI on every push lint → unit tests → build → (optional) e2e → deploy preview URL per pull request · cache-forever hashed assets Testing pyramid, frontend edition many component tests · a few end-to-end flows (login, checkout)
PLATE 9 — The build turns your code into a few small static files that a CDN serves.
Chapter 9 · Testing & deploying

Prove it works, then publish it

$ npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom
// TaskForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { vi, test, expect } from 'vitest';
import { TaskForm } from './App';

test('submits a trimmed title and clears the field', async () => {
  const onAdd = vi.fn();
  render(<TaskForm onAdd={onAdd} />);
  await userEvent.type(screen.getByLabelText(/new task/i), '  Buy milk ');
  await userEvent.click(screen.getByRole('button', { name: /add/i }));
  expect(onAdd).toHaveBeenCalledWith('Buy milk');
  expect(screen.getByLabelText(/new task/i)).toHaveValue('');
});
$ npm run build                       # → dist/
$ npx vercel --prod                    # or Netlify, Cloudflare Pages, GitHub Pages
# set VITE_API_URL for production; allow your site's origin in the API's CORS list
query by role
test like a user: find things by label and role, not CSS class
next steps
TypeScript, TanStack Query, a design system, Playwright e2e, and Next.js if you need SSR/SEO
Say it like a pro

"Tested like a user would use it, built by Vite, deployed to a CDN, and wired to the API through env config."