Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 25 min

Project: an interactive course catalogue

By the end of this chapter, you'll be able to

  • Create a React project with Vite and organise it into components
  • Separate the logic (tested pure functions) from the display (components)
  • Combine search, filter, sort and favourites in a single consistent state
  • Keep favourites in the browser with an effect

Creating the project

Vite creates a ready-to-use React project:

npm create vite@latest catalogue -- --template react
cd catalogue
npm install
npm run dev        # opens http://localhost:5173

The code is organised into three files:

src/
├── logic.js        ← pure functions: filter, sort, toggle (tested)
├── components.jsx  ← CourseCard, FilterBar, CourseList
└── App.jsx         ← the state and the assembly

A student's action updates the state through a copy, and the cycle starts again.

Step 5 of 5
Text description of the animation
  1. Everything that can change is in the App component's state, in a single place.
  2. A pure function filters and sorts the list. It does not depend on React: it is tested in plain JavaScript.
  3. The visible list is never stored: it is recomputed on every render.
  4. Components receive what they must display through their props.
  5. A student's action updates the state through a copy, and the cycle starts again.

The logic, tested

const COURSES = [
  { slug: "python", title: "Python: your first steps", level: "Beginner", minutes: 95 },
  { slug: "sql", title: "SQL: your first queries", level: "Beginner", minutes: 80 },
  { slug: "networks", title: "Networks: IP addresses and routing", level: "Intermediate", minutes: 125 },
  { slug: "docker", title: "Docker: containers", level: "Intermediate", minutes: 125 },
  { slug: "api", title: "Building a web API with Node.js", level: "Intermediate", minutes: 125 },
  { slug: "ai", title: "Generative AI", level: "Beginner", minutes: 105 },
];

function normalise(text) {
  return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
}

function visible(courses, { search = "", level = "all", sort = "title" }) {
  const t = normalise(search);
  const list = courses.filter((c) =>
    (level === "all" || c.level === level) && normalise(c.title).includes(t));
  const compare = sort === "duration"
    ? (a, b) => a.minutes - b.minutes || a.title.localeCompare(b.title)
    : (a, b) => a.title.localeCompare(b.title);
  return [...list].sort(compare);
}

function test(name, check) { console.log(check() ? "✓" : "✗", name); }
const slugs = (list) => list.map((c) => c.slug).join(",");

test("search ignores case", () => slugs(visible(COURSES, { search: "QUERIES" })) === "sql");
test("filter by level", () => visible(COURSES, { level: "Beginner" }).length === 3);
test("sort by duration then title", () => slugs(visible(COURSES, { sort: "duration" })) === "sql,python,ai,api,docker,networks");
test("the original list is not modified", () => { visible(COURSES, { sort: "duration" }); return COURSES[0].slug === "python"; });
test("no result", () => visible(COURSES, { search: "cobol" }).length === 0);
✓ search ignores case
✓ filter by level
✓ sort by duration then title
✓ the original list is not modified
✓ no result

normalize("NFD") separates letters from their accents, which the regular expression then removes: searching for "cafe" would find "café". The [...list] before sort is essential, because sort modifies the array it is called on.

The assembly

import { useEffect, useState } from "react";
import { COURSES, visible, toggle } from "./logic.js";
import { FilterBar, CourseList } from "./components.jsx";

function readFavourites() {
  try { return JSON.parse(localStorage.getItem("favourites")) ?? []; }
  catch { return []; }
}

export default function App() {
  const [options, setOptions] = useState({ search: "", level: "all", sort: "title" });
  const [favourites, setFavourites] = useState(readFavourites);

  useEffect(() => {
    try { localStorage.setItem("favourites", JSON.stringify(favourites)); } catch { /* storage unavailable */ }
  }, [favourites]);

  const list = visible(COURSES, options);
  return (
    <main>
      <h1>Course catalogue</h1>
      <FilterBar options={options} onChange={setOptions} />
      <p role="status">{list.length} course{list.length === 1 ? "" : "s"} found</p>
      {list.length === 0
        ? <p>No course matches. Try another word or the level “all”.</p>
        : <CourseList courses={list} favourites={favourites} onFavourite={(slug) => setFavourites(toggle(favourites, slug))} />}
    </main>
  );
}
  • useState(readFavourites): by passing the function (without parentheses), React only reads the storage once, on the first render;
  • the effect saves the favourites whenever favourites changes;
  • the try / catch protects against a browser where storage is blocked (private browsing).

Your turn

Worked exercise

Project: the complete catalogue

  1. Create the project with Vite and the three files.
  2. Add a "favourites only" filter to the logic (favouritesOnly: true) and write its test.
  3. Write the FilterBar (search field, level drop-down, sort drop-down, "favourites only" box) and CourseList components.
  4. Check on a phone, or with the browser's mobile view: everything must be usable with one thumb, at 360 pixels wide.
Hint 1
visible now also receives the list of favourites: visible(courses, options, favourites).
Hint 2
Each FilterBar control calls onChange({ ...options, field: newValue }).
Show the solution and common mistakes
const COURSES = [
  { slug: "python", title: "Python", level: "Beginner", minutes: 95 },
  { slug: "sql", title: "SQL", level: "Beginner", minutes: 80 },
  { slug: "docker", title: "Docker", level: "Intermediate", minutes: 125 },
];

function visible(courses, { level = "all", favouritesOnly = false }, favourites = []) {
  return courses.filter((c) =>
    (level === "all" || c.level === level) && (!favouritesOnly || favourites.includes(c.slug)));
}

console.log(visible(COURSES, { favouritesOnly: true }, ["docker", "sql"]).map((c) => c.slug));
console.log(visible(COURSES, { favouritesOnly: true, level: "Beginner" }, ["docker", "sql"]).map((c) => c.slug));
console.log(visible(COURSES, {}, ["docker"]).length);
["sql","docker"]
["sql"]
3
export function FilterBar({ options, onChange }) {
  return (
    <form className="filters" onSubmit={(e) => e.preventDefault()}>
      <label>Search
        <input value={options.search} onChange={(e) => onChange({ ...options, search: e.target.value })} />
      </label>
      <label>Level
        <select value={options.level} onChange={(e) => onChange({ ...options, level: e.target.value })}>
          <option value="all">All</option>
          <option>Beginner</option>
          <option>Intermediate</option>
        </select>
      </label>
      <label>Sort by
        <select value={options.sort} onChange={(e) => onChange({ ...options, sort: e.target.value })}>
          <option value="title">Title</option>
          <option value="duration">Duration</option>
        </select>
      </label>
      <label>
        <input type="checkbox" checked={options.favouritesOnly ?? false}
          onChange={(e) => onChange({ ...options, favouritesOnly: e.target.checked })} />
        Favourites only
      </label>
    </form>
  );
}

Each field has a <label>: a screen reader announces its role, and tapping the text activates the field, which helps on a small screen.

Common mistakes:

  • Storing the filtered list in a second state: it gets out of sync as soon as you forget to recompute it after a filter change.
  • Forgetting e.preventDefault() in onSubmit: pressing Enter in the field reloads the whole page.
  • Reading e.target.value for a checkbox: its value is in e.target.checked.

Summary

  1. 1Vite creates a React project; the pure logic, the components and the assembly are separated.
  2. 2The logic (filter, sort, toggle) is tested in plain JavaScript, without React.
  3. 3State is gathered in a single place; the visible list is recomputed on every render.
  4. 4Sort a copy ([...list].sort or toSorted), never the state itself.
  5. 5An effect keeps the favourites in the browser, protected by a try / catch.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.