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.
Return elements rather than HTML strings: callers can append them anywhere, listeners can be attached safely, and user text never becomes markup.
Keep components free of global state: everything they need comes in through parameters ("props"). That is what makes them reusable and testable.
Accessibility belongs inside the component (labels, roles, keyboard support), so every use is accessible by default.
Web Components (customElements.define) package the same idea as a native HTML tag with lifecycle callbacks; the function approach here is the simplest form and maps directly onto frameworks' components.
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.
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.
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.
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
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.
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 explanationreusable 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 predictionreusable 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.
Debuggingreusable 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 generationreusable 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 reviewreusable 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.