Nine spreads, from a blank HTML file to a deployed, accessible, fast React app that talks to an API.
"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.
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>
<a> for navigation. Never a clickable <div>.<img src alt="Tom's red bike">; empty alt="" if decorative"Landmarks, real buttons and links, labelled inputs. Accessibility starts in the markup."
: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; }
--brand: one place to change a theme!important"Design tokens as custom properties, flex for one dimension, grid for two."
/* 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 */
prefers-reduced-motion and prefers-color-scheme."Mobile-first, fluid type, content-driven breakpoints, and no horizontal scroll at any width."
// 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();
textContent.fetch returns a promise: await it, handle failure"UI is a function of state: update the data, re-render, and never inject untrusted HTML."
$ 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>;
}
"Small components, state lifted to the owner, immutable updates, stable keys."
// 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
"One API wrapper, a status for every fetch, abort stale requests, and a designed empty and error state."
$ 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>);
}
index.html for unknown paths, or deep links 404"Client-side routing with a 404 route, and accessible inline validation on every form."
rem.width/height set, loading="lazy", modern formats (WebP/AVIF).// 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
"Keyboard and screen-reader tested, Core Web Vitals in the green, and routes code-split."
$ 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
"Tested like a user would use it, built by Vite, deployed to a CDN, and wired to the API through env config."