JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 15: Interactive Application ArchitectureLesson 72 of 150About 45 minutes

Lesson 72: Reusable UI components

01Opening question

You built a great card for one product. Now you need fifty, each with different data. Copy and paste?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

A component function takes data (and options) and returns an element. Call it as often as you like with different data.

function Badge(text, tone = "info") {
  const span = document.createElement("span");
  span.className = "badge " + tone;
  span.textContent = text;
  return span;
}
document.querySelector("#host").append(Badge("New"), Badge("Sold out", "danger"));
console.log(document.querySelector("#host").innerHTML);

03Objective and prerequisites

Learning objective: Write reusable UI components as functions that take data and options and return elements, with events reported through callbacks.

You need: Lesson 71: Separating data, logic and presentation, Lesson 60: Building interactive components

Skills practised: Browser application architecture, Reusable UI components.

04Explanation

A reusable component is a function that builds one piece of interface from the data you give it: ProductCard(product) returns a card element.

Options with defaults (tone = "info") let the same component cover small variations without copies.

Components can contain other components: a ProductList calls ProductCard for each product.

To report clicks, accept a callback such as onSelect. The component calls it; the page decides what selection means.

05Definitions

Reusable component
A function or class that builds a piece of interface from data and options so it can be used many times.
Props
The data and options passed into a component.
Callback prop
A function passed into a component that it calls to report events, such as onSelect.
Composition
Building larger components from smaller ones.
Web Component
A custom HTML element defined with customElements.define.

Open the full glossary

06Visual learning object

Component lifecycle model. Create, update and remove component instances and watch props flow in, callbacks flow out and listeners being cleaned up.

Loading the interactive object…

Open the full Component lifecycle model page with its guided experiment.

07Examples

ex-072-01A product card component Browser page (sandboxed preview)

One function, many cards, each built from its own data.

function ProductCard({ name, price, sale = false }) {
  const card = document.createElement("article");
  card.className = "card";
  const title = document.createElement("h3");
  title.textContent = name;
  const p = document.createElement("p");
  p.textContent = "$" + price + (sale ? " (sale)" : "");
  card.append(title, p);
  return card;
}
const products = [{ name: "Lamp", price: 30 }, { name: "Mug", price: 8, sale: true }];
document.querySelector("#grid").append(...products.map(ProductCard));
console.log(document.querySelectorAll(".card").length, document.querySelector("#grid").textContent);
Sample input
None
Expected output
2 Lamp$30Mug$8 (sale)
Common mistake
Copying the card markup for each product and fixing a bug in only one copy.
Try this
Add an optional image URL prop.
Source
examples/ex-072-01-card.js

ex-072-02Reporting events with callbacks Browser page (sandboxed preview)

The component calls onSelect; the page decides what happens.

function SelectableList(items, { onSelect }) {
  const ul = document.createElement("ul");
  for (const item of items) {
    const li = document.createElement("li");
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = item.label;
    button.addEventListener("click", () => onSelect(item));
    li.append(button);
    ul.append(li);
  }
  return ul;
}
const list = SelectableList([{ id: "s", label: "Small" }, { id: "l", label: "Large" }], {
  onSelect: (item) => { document.querySelector("#chosen").textContent = "Chosen: " + item.id; }
});
document.querySelector("#list").replaceWith(list);
list.querySelectorAll("button")[1].click();
console.log(document.querySelector("#chosen").textContent);
Sample input
None
Expected output
Chosen: l
Common mistake
Making the component write to #chosen itself, so it only works on one page.
Try this
Mark the chosen button with aria-pressed.
Source
examples/ex-072-02-callback.js

ex-072-03Composing components Browser page (sandboxed preview)

Small components combine into bigger ones.

const el = (tag, props = {}, ...children) => {
  const node = Object.assign(document.createElement(tag), props);
  node.append(...children);
  return node;
};
const Avatar = (name) => el("span", { className: "avatar", textContent: name[0] });
const UserRow = (user) => el("li", {}, Avatar(user.name), " " + user.name);
const UserList = (users) => el("ul", {}, ...users.map(UserRow));
document.querySelector("#app").append(UserList([{ name: "Ada" }, { name: "Lin" }]));
console.log(document.querySelector("#app ul").children.length, document.querySelector("#app").textContent);
Sample input
None
Expected output
2 A AdaL Lin
Common mistake
Writing one giant function that builds the whole page.
Try this
Add a Badge component for admins.
Source
examples/ex-072-03-composition.js

ex-072-04A native custom element Browser page (sandboxed preview)

customElements.define turns a class into a real HTML tag.

class PriceTag extends HTMLElement {
  connectedCallback() {
    const amount = Number(this.getAttribute("amount"));
    const currency = this.getAttribute("currency") || "USD";
    this.textContent = new Intl.NumberFormat("en-CA", { style: "currency", currency }).format(amount);
  }
}
customElements.define("price-tag", PriceTag);
console.log(document.querySelector("price-tag").textContent);
const extra = document.createElement("price-tag");
extra.setAttribute("amount", "3");
extra.setAttribute("currency", "CAD");
document.body.append(extra);
console.log(extra.textContent);
Sample input
None
Expected output
$12.50 $3.00
Common mistake
Forgetting that custom element names must contain a hyphen.
Try this
Re-render when the amount attribute changes with attributeChangedCallback.
Source
examples/ex-072-04-custom-element.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The component only works once

Use props instead of globals.

const user = { name: "Ada" };
function Greeting() {
  const p = document.createElement("p");
  p.textContent = "Hello, " + user.name;
  return p;
}
document.querySelector("#host").append(Greeting({ name: "Lin" }));
console.log(document.querySelector("#host").textContent);

An alert component

Build a component with options and defaults.

function Alert(message, { tone = "info", dismissible = false } = {}) {
  // TODO: return a div with class "alert <tone>", role "status",
  // the message as text, and (if dismissible) a button "Dismiss"
  // that removes the div
}
const host = document.querySelector("#host");
host.append(Alert("Saved"), Alert("Payment failed", { tone: "error", dismissible: true }));
host.querySelector("button").click();
console.log(host.children.length, host.firstElementChild.className);

A to-do list from components

Compose components with callbacks.

// TodoItem(todo, { onToggle }) -> li with a checkbox (checked = todo.done)
//   and the text; changing the checkbox calls onToggle(todo.id)
// TodoList(todos, { onToggle }) -> ul of TodoItem
// App: state = [{id:1,text:"Read",done:false},{id:2,text:"Cook",done:false}]
//   render() replaces #app's content with TodoList(state, { onToggle })
//   onToggle flips done and re-renders.
// Click the second checkbox, then log the done flags joined with ",".

09Prediction

Commit to an answer first, then run the real code to compare.

function Tag(text, { upper = false } = {}) {
  return upper ? text.toUpperCase() : text;
}
console.log(Tag("new"), Tag("sale", { upper: true }));

What is printed?

10Debugging investigation

Every chip turns selected

Selecting one filter chip marks all chips as selected, including ones created later.

const defaults = { selected: false };
function Chip(label, options = defaults) {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = label;
  button.addEventListener("click", () => {
    options.selected = !options.selected;
    button.setAttribute("aria-pressed", String(options.selected));
  });
  button.isSelected = () => options.selected;
  return button;
}
const a = Chip("Red");
const b = Chip("Blue");
document.getElementById("chips").append(a, b);
a.click();
console.log(a.isSelected(), b.isSelected());

More cases in the Debugging Detective Laboratory

11Practical scenario

Component libraries

A company's design system publishes Button, Alert, Card and Modal components. Product teams pass data and callbacks in and never copy markup, so a fix to Modal's focus handling reaches every page at once.

const uses = { Button: 140, Card: 85, Modal: 23 };
console.log("Fix Modal once, update", uses.Modal, "screens");

12Knowledge check

1. What makes a component reusable?

  • It reads global variables
  • Everything it needs comes in through parameters
  • It is long
  • It uses innerHTML

2. Why accept an onSelect callback instead of changing the page inside the component?

  • Callbacks are faster
  • The page decides what selection means, so the component works anywhere
  • It is required by the DOM
  • To avoid events

3. Why do all cards show the same title?

const current = { title: "Lamp" };
function Card(item) {
  return Object.assign(document.createElement("h3"), { textContent: current.title });
}
  • The component ignores its parameter and reads a global
  • map is broken
  • append copies
  • h3 cannot change

4. Badge("Hi") with default tone "info" gives className?

function Badge(text, tone = "info") { const s = document.createElement("span"); s.className = "badge " + tone; return s; }
  • badge
  • badge info
  • info
  • undefined

5. Why return elements instead of HTML strings?

  • Strings are not allowed
  • Elements can carry listeners and user text stays text
  • Elements are smaller
  • Strings cannot be appended

6. Where should keyboard support for a dropdown live?

  • In every page that uses it
  • Inside the dropdown component
  • In CSS
  • Nowhere

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The component only works once: Prints Hello, Lin; Works with other data
  • An alert component: Prints 1 alert info; Has role status; No button unless dismissible
  • A to-do list from components: Prints false,true; The checkbox reflects state; TodoItem works alone

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-15-interactive-application-architecture/lesson-072-reusable-ui-components/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Components are functions from data and options to elements.
  • Defaults cover variations; composition builds bigger pieces.
  • Callbacks report events without tying the component to a page.
  • Keep components free of globals and accessible by default.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation reusable UI components
Context: I am learning reusable UI components in JavaScript.
Task: Explain function components with props, defaults, callbacks and composition.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction reusable UI components drill
Context: I have practised reusable UI components.
Task: Give me six component functions and calls and ask what each renders.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging reusable UI components bug
Context: My card component shows the same product everywhere.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation reusable UI components practice
Context: I finished the reusable UI components exercises.
Task: Create three exercises that build components and compose them.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review reusable UI components review
Context: Here is my code that uses reusable UI components.
Task: Review my components for globals, HTML strings with user data and missing accessibility.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.