Lab: A Filterable, Sortable Product Table
Build a real React project with Vite: typed data, a table of rows keyed by SKU, live filtering, and sortable columns announced with aria-sort — then drive it in a browser to check every behaviour.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: typed data first
- Step 2: a static table from the data
- Step 3: filter with two inputs
- Step 4: sortable headers
- Step 5: check it like a user
- Check your understanding
- Apply it
- Review prompt
Lessons of React Components & State
- From Mockup to Component Tree Concept · 20 min
- JSX, Typed Props and Composition Worked example · 25 min
- State, Events and Immutable Updates Worked example · 25 min
- Lists, Keys and When React Re-renders Concept · 20 min
- Lab: A Filterable, Sortable Product Table Lab · 30 min
- Check: Predict the Component Behavior Knowledge check · 6 questions
What you will learn
- Break a UI design into a component hierarchy and implement it with JSX, typed props and composition through children.
- Handle user events and manage local state with useState, updating objects and arrays immutably and lifting shared state to the closest common parent.
- Render lists with stable keys and conditional content, and predict when a component re-renders and when its state is preserved or reset.
Prerequisites: JavaScript Foundations
01. Goal and setup
This lab assembles the whole skill into one working page: a product table you can search, filter by stock, and sort by clicking a column header — every row keyed by a stable SKU, every count derived during render, every control labelled and operable by keyboard. It is the React rebuild of the plain-JavaScript filterable list lab, so you can compare the two models line by line. If you have not created a Vite project before, the tooling lessons explain what the dev server and build do.
You need: Node 22 or later with npm. This lab was checked on 26 November 2026 with what npm install resolved from the package.json below: React 19.3.1, Vite 8.4.0, @vitejs/plugin-react 6.3.0 and TypeScript 7.0.2. The expected outputs after steps 2 to 5 list the visible text of the status line and of the table rows, read row by row; they were checked by driving the page with Playwright 1.64.1 and Chromium 156. Vite's own start-up time and bundle sizes vary by machine and version.
In an empty folder, create this structure:
product-table/
├── package.json
├── tsconfig.json
├── vite.config.ts
├── index.html
└── src/
├── main.tsx
├── products.ts
├── App.tsx
└── styles.css{
"name": "product-table-lab",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@types/react": "^19.3.3",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.3.0",
"typescript": "~7.0.2",
"vite": "^8.4.0"
}
}Run npm install once, after saving package.json: npm reads the versions from it, resolves the whole tree and writes a lockfile so the next install reproduces exactly this setup. Then add the three config files. The TypeScript settings matter: strict is on, and lib includes ES2023 and the DOM so array and input types resolve. In tsconfig.json: "target": "es2022", "lib": ["es2023", "dom", "dom.iterable"], "module": "esnext", "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noEmit": true, "skipLibCheck": true and "types": ["vite/client"], with "include": ["src", "vite.config.ts"]. The last two options are not decoration. vite/client tells TypeScript what importing a .css file means; TypeScript 7 checks such side-effect imports and otherwise stops with error TS2882 on import './styles.css'. skipLibCheck stops it type-checking Vite's own declaration files, which vite.config.ts pulls in and which expect Node's types; without it, npx tsc --noEmit reports about forty errors from node_modules. The other three files are short:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({ plugins: [react()] });
// index.html
// <!doctype html>
// <html lang="en">
// <head><meta charset="UTF-8" /><title>Product table</title></head>
// <body>
// <div id="root"></div>
// <script type="module" src="/src/main.tsx"></script>
// </body>
// </html>
// src/styles.css
// body { font-family: system-ui, sans-serif; margin: 2rem; }
// table { border-collapse: collapse; }
// th, td { padding: 0.5rem 0.75rem; border: 1px solid #ccc; text-align: left; }
// :focus-visible { outline: 3px solid #1a5fb4; outline-offset: 2px; }import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('index.html has no element with id="root"');
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
); VITE v8.4.0 ready in 446 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose02. Step 1: typed data first
export type Product = {
sku: string;
name: string;
category: string;
pricePence: number;
inStock: boolean;
};
export const products: Product[] = [
{ sku: 'B01', name: 'Bagels', category: 'Bakery', pricePence: 190, inStock: true },
{ sku: 'B02', name: 'Bread', category: 'Bakery', pricePence: 240, inStock: true },
{ sku: 'F01', name: 'Apples', category: 'Fruit', pricePence: 180, inStock: true },
{ sku: 'F02', name: 'Bananas', category: 'Fruit', pricePence: 95, inStock: true },
{ sku: 'F03', name: 'Cherries', category: 'Fruit', pricePence: 349, inStock: false },
{ sku: 'V01', name: 'Carrots', category: 'Veg', pricePence: 70, inStock: true },
{ sku: 'V02', name: 'Leeks', category: 'Veg', pricePence: 210, inStock: true },
{ sku: 'V03', name: 'Spinach', category: 'Veg', pricePence: 165, inStock: false },
];Prices are integer pence, because floating-point money is its own lesson in pain; a small money helper will format them. Every row carries an sku chosen by the data, which will become the key in step 3 — decided now, so no list ever falls back to positional identity. Run the type check now: main.tsx already imports App, which step 2 creates, so exactly one error is expected, and none comes from products.ts.
src/main.tsx(3,17): error TS2307: Cannot find module './App' or its
corresponding type declarations.03. Step 2: a static table from the data
import { products, type Product } from './products';
const money = (pence: number) => `£${(pence / 100).toFixed(2)}`;
function ProductRow({ product }: { product: Product }) {
return (
<tr>
<th scope="row">{product.name}</th>
<td>{product.category}</td>
<td>{money(product.pricePence)}</td>
<td>{product.inStock ? 'In stock' : 'Out of stock'}</td>
</tr>
);
}
export default function App() {
return (
<main>
<h1>Product table</h1>
<table>
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
<th scope="col">Availability</th>
</tr>
</thead>
<tbody>
{products.map((p) => (
<ProductRow key={p.sku} product={p} />
))}
</tbody>
</table>
</main>
);
}Reload the dev page: eight rows, priced and stocked exactly as in products.ts, and a quiet console. noUnusedLocals in the tsconfig keeps the file honest: if a prop or variable is not used, npx tsc --noEmit fails before the browser ever runs; run it now and it prints nothing, because App exists. Each row is a ProductRow component receiving the product as a typed prop and carrying its sku as key. The product name is a <th scope="row"> so screen readers announce which row a cell belongs to. styles.css can stay minimal — system font, collapsed borders, generous padding, and one rule that matters: a visible :focus-visible outline, because keyboard users must always see where they are.
Bagels Bakery £1.90 In stock
Bread Bakery £2.40 In stock
Apples Fruit £1.80 In stock
Bananas Fruit £0.95 In stock
Cherries Fruit £3.49 Out of stock
Carrots Veg £0.70 In stock
Leeks Veg £2.10 In stock
Spinach Veg £1.65 Out of stock04. Step 3: filter with two inputs
import { useState } from 'react';
import { products, type Product } from './products';
export default function App() {
const [query, setQuery] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
// filter() returns new arrays, so sort() later never touches the original data.
const needle = query.trim().toLowerCase();
const visible = products
.filter((p) => p.name.toLowerCase().includes(needle))
.filter((p) => !inStockOnly || p.inStock);
return (
<main>
<h1>Product table</h1>
<label htmlFor="search">Search products</label>{' '}
<input
id="search"
type="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>{' '}
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(event) => setInStockOnly(event.target.checked)}
/>{' '}
In stock only
</label>
<p role="status">
{visible.length} of {products.length} products shown
</p>
{/* ... the table from step 2, mapping over visible instead of products */}
</main>
);
}Two pieces of state, both owned by App because the table below needs their result. The visible list is derived: computed during render from the raw data and the two states, never stored. The status line is a live region (role="status"), so assistive technology announces "3 of 8 products shown" as the list narrows — the same pattern as the count line in the DOM lab. Both inputs are labelled and controlled. Try it: type an and only Bananas remains; clear the box and tick In stock only, and the two out-of-stock items disappear.
after typing "an": 1 of 8 products shown
Bananas Fruit £0.95 In stock
in stock only: 6 of 8 products shown
Bagels Bakery £1.90 In stock
Bread Bakery £2.40 In stock
Apples Fruit £1.80 In stock
Bananas Fruit £0.95 In stock
Carrots Veg £0.70 In stock
Leeks Veg £2.10 In stock05. Step 4: sortable headers
type SortKey = 'name' | 'price';
type SortDir = 'asc' | 'desc';
type Sort = { key: SortKey; dir: SortDir };
function SortHeader({
label,
sortKey,
sort,
onToggle,
}: {
label: string;
sortKey: SortKey;
sort: Sort;
onToggle: (key: SortKey) => void;
}) {
const ariaSort =
sort.key === sortKey
? sort.dir === 'asc'
? 'ascending'
: 'descending'
: 'none';
const marker = sort.key === sortKey ? (sort.dir === 'asc' ? ' ↑' : ' ↓') : '';
return (
<th scope="col" aria-sort={ariaSort}>
<button type="button" onClick={() => onToggle(sortKey)}>
{label}
{marker}
</button>
</th>
);
}A clickable column header is a <button> inside the <th> — real button semantics, reachable by Tab and triggered by Enter, never a div with an onClick. The aria-sort attribute on the th states the current order programmatically, so the sort direction is not communicated by the arrow glyph alone. The sort state is one object; toggleSort receives the previous value through the updater form because the next direction depends on it.
const [sort, setSort] = useState<Sort>({ key: 'name', dir: 'asc' });
function toggleSort(key: SortKey) {
setSort((prev) =>
prev.key === key && prev.dir === 'asc'
? { key, dir: 'desc' }
: { key, dir: 'asc' },
);
}
const visible = products
.filter((p) => p.name.toLowerCase().includes(needle))
.filter((p) => !inStockOnly || p.inStock)
.sort((a, b) => {
if (sort.key === 'name') {
return sort.dir === 'asc'
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name);
}
return sort.dir === 'asc'
? a.pricePence - b.pricePence
: b.pricePence - a.pricePence;
});In the header row, render <SortHeader label="Product" sortKey="name" sort={sort} onToggle={toggleSort} /> and the same for Price, with plain th cells for Category and Availability. Because filter already produced a new array, calling sort on it cannot rearrange the module-level data — the immutable-update discipline from the state lesson doing quiet work.
Price aria-sort: ascending
Carrots Veg £0.70 In stock
Bananas Fruit £0.95 In stock
Spinach Veg £1.65 Out of stock
Apples Fruit £1.80 In stock
Bagels Bakery £1.90 In stock
Leeks Veg £2.10 In stock
Bread Bakery £2.40 In stock
Cherries Fruit £3.49 Out of stock
after second Price click: descending
first row now:
Cherries Fruit £3.49 Out of stock06. Step 5: check it like a user
Before shipping, read your own interface the way a user does. Build the production bundle with npm run build and serve it with npm run preview. With the versions above, the build reported one JavaScript chunk of 221.59 kB (69.37 kB gzipped), almost all of it React itself; other versions give slightly different numbers. Then put the mouse away. Tab from the search box: the focus outline moves to the In stock only checkbox and then to the Product column-header button. Because the table starts sorted by product name ascending, pressing Enter toggles the sort to descending, and aria-sort updates to match. With the keyboard alone you can search, filter and sort; that is the accessibility bar every component in this course has to clear.
Tab path reaches: Product ↑
Product aria-sort after Enter: descending
console errors: none07. Check your understanding
08. Apply it
Extend the lab in two directions, each with a written prediction first. Add a third sortable column for Category, reusing SortHeader unchanged. Then add a per-category count line derived from visible, announced by the same status region. Finish by taking the evidence the practice brief for this skill asks for: React DevTools screenshots showing which components re-render on a search, on a stock toggle and on a sort — with your one-sentence prediction written above each.
09. Review prompt
Without looking back: list the four values the table depends on (query, stock flag, sort, visible list), say which three are stored in state and why the fourth is derived during render instead, and recount the three ways the table stays accessible — labels, keyboard operation of the sort buttons, and the live status line.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.