Building Reusable UI Components with Pure JavaScript
Published by Brayan K
Master the foundations of component architecture without frameworks. Learn Custom Elements, Shadow DOM, slots, state management, and patterns used by React, Vue, and Svelte.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A reusable component owns a small, explicit contract
Start with the DOM it owns, the inputs it accepts, the state it changes and the way it reports changes. Reusability is not just wrapping markup in a function. Two instances must work independently, and a caller must know how to update and dispose of each one.
function mountCounter(root) {
const button = document.createElement("button");
button.type = "button";
// This closure belongs to this one mounted instance.
let count = 0;
const paint = () => { button.textContent = String(count); };
const onClick = () => { count++; paint(); };
button.addEventListener("click", onClick);
paint(); root.append(button);
return { button, destroy() { button.removeEventListener("click", onClick); button.remove(); } };
}
const firstRoot = document.createElement("div"), secondRoot = document.createElement("div");
document.getElementById("app").append(firstRoot, secondRoot);
const first = mountCounter(firstRoot), second = mountCounter(secondRoot);
first.button.click(); first.button.click(); second.button.click();
console.log(first.button.textContent, second.button.textContent);
first.destroy(); second.destroy();
// ✅ Expected output:
// 2 1Use a native button for button behavior; do not rebuild keyboard activation with a clickable div unless the application has a specific reason and implements the full behavior. This page designs plain-DOM component contracts. Web Components & Custom Elements owns custom-element registration, lifecycle callbacks, Shadow DOM and slots in depth.
Instance state and selectors must stay within the instance
const first = document.createElement("section"), second = document.createElement("section");
for (const root of [first, second]) {
const output = document.createElement("span"); output.className = "component-output";
output.textContent = "initial"; root.append(output);
}
document.getElementById("app").append(first, second);
second.querySelector(".component-output").textContent = "second";
console.log(first.textContent, second.textContent);
// ✅ Expected output:
// initial secondPrefer retained references to the elements a component creates or selectors scoped to its root. Avoid reusing a fixed id across instances. Accessible relationships such as aria-controls need document-unique IDs, even when the JavaScript selector is scoped.
const button = document.createElement("button");
button.setAttribute("disabled", "false");
console.log(button.disabled);
button.disabled = false;
console.log(button.hasAttribute("disabled"));
// ✅ Expected output:
// true
// falseProperties and attributes are different interfaces. A boolean API should reject the string "false" instead of coercing it to true. For ARIA states such as aria-expanded, set the textual value true or false deliberately; removing a native boolean attribute is a different operation.
Repeated rendering must not register repeated behavior
const button = document.createElement("button"); let calls = 0;
function update() {
button.textContent = "Run";
button.addEventListener("click", () => calls++);
}
update(); update(); button.click();
console.log(calls);
// ✅ Expected output:
// 2const button = document.createElement("button"); let calls = 0;
const onClick = () => calls++;
button.addEventListener("click", onClick);
button.textContent = "First"; button.textContent = "Second";
button.click(); button.removeEventListener("click", onClick); button.click();
console.log(calls);
// ✅ Expected output:
// 1Separate mounting listeners from updating display. Decide whether a component can reconnect after disposal; the brief uses a terminal destroy method. JavaScript Memory Management & Garbage Collection owns subscriptions and cleanup lifetime. Replacing whole subtrees can also discard input state and focus; Virtual DOM Concepts & Efficient UI Updates owns node identity and patching.
State, visibility and accessibility attributes must agree
const button = document.createElement("button"), panel = document.createElement("div");
button.type = "button"; button.textContent = "Details";
function reflect(open) {
panel.hidden = !open;
button.setAttribute("aria-expanded", String(open));
}
reflect(false);
console.log(panel.hidden, button.getAttribute("aria-expanded"));
reflect(true);
console.log(panel.hidden, button.getAttribute("aria-expanded"));
// ✅ Expected output:
// true false
// false trueA disclosure is a button controlling a section of content. Native buttons provide Enter and Space activation; add one click handler rather than separate key handlers that can double-toggle. The checked attribute states are necessary parts of the pattern, not a complete assistive-technology certification.
const button = document.createElement("button"), panel = document.createElement("div");
const input = document.createElement("input"); input.setAttribute("aria-label", "Disclosure note");
button.textContent = "Details"; button.type = "button";
panel.append(input); document.getElementById("app").append(button, panel);
input.focus();
if (panel.contains(document.activeElement)) button.focus();
panel.hidden = true;
console.log(document.activeElement === button, panel.hidden);
// ✅ Expected output:
// true trueProgrammatic collapse may occur while focus is inside the panel. Move it to the controlling button before hiding that content. If an entire component is removed from a screen, the surrounding application must choose an appropriate next focus target; a generic component cannot infer that navigation decision.
Publish a chosen event contract instead of exposing internal nodes
const root = document.createElement("div"), parent = document.createElement("section");
parent.append(root); document.getElementById("app").append(parent);
const seen = [];
parent.addEventListener("disclosurechange", event => seen.push(event.detail.open));
root.dispatchEvent(new CustomEvent("disclosurechange", { bubbles: true, detail: Object.freeze({ open: true }) }));
console.log(seen.join(","));
// ✅ Expected output:
// trueSpecify whether programmatic updates emit the same event as user actions, whether no-op updates emit, and whether listeners can cancel a proposed change. The brief emits after a real state change, including API changes, and does not make the event cancellable. Events owns DOM event propagation.
Shadow DOM can scope structure and styling, but it is not a security boundary. Events crossing a shadow boundary involve composed behavior and retargeting; slots distribute light-DOM content instead of copying it. Those platform details belong to Web Components & Custom Elements. Do not add Shadow DOM merely to avoid defining ownership and lifecycle.
Validate a mount before moving content into its container
function requireEmptyRoot(root) {
if (!(root instanceof HTMLElement) || root.childNodes.length !== 0)
throw new TypeError("root must be an empty HTML element");
}
const root = document.createElement("section"), original = document.createElement("p");
root.append(original);
try { requireEmptyRoot(root); }
catch (error) { console.log(error.name, root.firstChild === original); }
// ✅ Expected output:
// TypeError trueThe brief requires an empty root and a detached content element from the same document. It takes ownership of that content while mounted. This prevents accidental removal or movement of another component’s existing DOM. Labels are text; accepting an arbitrary HTML string would require a different trust contract. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns rendering untrusted content.
Guided exercise: reflect a controlled disclosure state
Fill the literal hints. One state value drives both the button’s ARIA state and the panel’s hidden property.
const button = document.createElement("button"), panel = document.createElement("div");
let open = true;
button.setAttribute("aria-expanded", String(___)); // 👉 replace ___ with open
panel.hidden = !___; // 👉 replace ___ with open
console.log(button.getAttribute("aria-expanded"), panel.hidden);
// ✅ Expected output:
// true falseIndependent brief: a disposable disclosure component
Implement mountDisclosure(root, options). Require an empty HTMLElement root, a trimmed text label of 1 through 80 UTF-16 code units, a detached HTMLElement content node in the same document, and a boolean initialOpen. Reject ancestor/self content before moving it. Create a native type=button control and a uniquely identified panel, using aria-controls and aria-expanded.
Return setOpen(boolean), getOpen() and idempotent destroy(). setOpen returns false for a no-op; otherwise it moves focus to the button when collapsing focused content, reflects state, and emits one bubbling disclosurechange event with a frozen detail object containing the open boolean. Clicks use the same path. destroy removes this component’s listener and nodes, returns true once, and makes later setOpen calls fail. It does not choose the application’s focus destination when the entire widget disappears.
let disclosureSerial = 0;
function mountDisclosure(root, { label, content, initialOpen = false }) {
if (!(root instanceof HTMLElement) || root.childNodes.length !== 0)
throw new TypeError("root must be an empty HTML element");
if (typeof label !== "string" || label.trim().length < 1 || label.trim().length > 80)
throw new TypeError("label must contain 1..80 trimmed code units");
if (!(content instanceof HTMLElement) || content.parentNode !== null ||
content === root || content.contains(root) || content.ownerDocument !== root.ownerDocument)
throw new TypeError("content must be a detached HTML element in this document");
if (typeof initialOpen !== "boolean") throw new TypeError("initialOpen must be boolean");
const doc = root.ownerDocument, button = doc.createElement("button"), panel = doc.createElement("div");
let id;
do { id = "lesson-disclosure-" + ++disclosureSerial; } while (doc.getElementById(id));
panel.id = id; panel.append(content);
button.type = "button"; button.textContent = label.trim();
button.setAttribute("aria-controls", id);
let open = initialOpen, destroyed = false;
function reflect() {
button.setAttribute("aria-expanded", String(open));
panel.hidden = !open;
}
function setOpen(value) {
if (destroyed) throw new Error("disclosure is destroyed");
if (typeof value !== "boolean") throw new TypeError("open must be boolean");
if (value === open) return false;
if (!value && panel.contains(doc.activeElement)) button.focus();
open = value; reflect();
root.dispatchEvent(new CustomEvent("disclosurechange", {
bubbles: true, detail: Object.freeze({ open })
}));
return true;
}
const onClick = () => setOpen(!open);
button.addEventListener("click", onClick);
reflect(); root.append(button, panel);
return Object.freeze({
setOpen,
getOpen: () => open,
destroy() {
if (destroyed) return false;
destroyed = true; button.removeEventListener("click", onClick);
button.remove(); panel.remove(); return true;
}
});
}
const root = document.createElement("section"), content = document.createElement("p");
const input = document.createElement("input"); input.setAttribute("aria-label", "Disclosure note"); content.append(input);
document.getElementById("app").append(root);
const events = []; root.addEventListener("disclosurechange", event => events.push(event.detail.open));
const widget = mountDisclosure(root, { label: "<b>Details</b>", content });
const button = root.querySelector("button"), panel = root.querySelector("div");
console.log(panel.hidden, button.getAttribute("aria-expanded"), button.querySelectorAll("b").length);
button.click(); input.focus(); widget.setOpen(false);
console.log(document.activeElement === button, events.join(","));
console.log(widget.setOpen(false), button.getAttribute("aria-controls") === panel.id);
console.log(widget.destroy(), widget.destroy(), root.childNodes.length);
try { widget.setOpen(true); }
catch (error) { console.log(error.message); }
// ✅ Expected output:
// true false 0
// true true,false
// false true
// true false 0
// disclosure is destroyedReference notes
The WAI disclosure pattern specifies button activation and expanded state. The platform guides for custom elements and Shadow DOM describe the separate platform features.
Practice quiz
What does this complete program print? const b=document.createElement("button");b.setAttribute("disabled","false");console.log(b.disabled);
- true
- false
- undefined
- TypeError
Answer: true. Native boolean attributes are true when present.
What does this complete program print? const b=document.createElement("button");b.setAttribute("aria-expanded","false");console.log(b.getAttribute("aria-expanded"));
- true
- false
- null
- undefined
Answer: false. ARIA state is the explicitly supplied string.
What does this complete program print? const b=document.createElement("button");let n=0;for(let i=0;i<2;i++)b.addEventListener("click",()=>n++);b.click();console.log(n);
- 0
- 1
- 2
- undefined
Answer: 2. Distinct listener functions both run.
What does this complete program print? const b=document.createElement("button");let n=0;const fn=()=>n++;b.addEventListener("click",fn);b.removeEventListener("click",fn);b.click();console.log(n);
- 1
- 2
- undefined
- 0
Answer: 0. Removal uses the original callback identity.
What does this complete program print? const e=document.createElement("p");e.textContent="<b>Label</b>";console.log(e.childElementCount);
- 0
- 1
- 2
- undefined
Answer: 0. A text label does not create HTML elements.
What should a disclosure do when programmatic collapse would hide the focused input?
- Keep focus hidden inside it
- Move focus to its controlling button before hiding the panel
- Remove all buttons from the document
- Set aria-expanded to true
Answer: Move focus to its controlling button before hiding the panel. The component can preserve a usable focus location when collapsing its own content.
Why use a unique panel id for each instance?
- IDs are required on every element
- It improves all JavaScript execution speed
- aria-controls must identify that instance’s panel without ambiguity
- It makes client state secret
Answer: aria-controls must identify that instance’s panel without ambiguity. A scoped JavaScript selector does not make duplicate document IDs unambiguous.
What does the brief’s destroy method establish?
- The browser immediately collects all memory
- Every external listener has been removed
- Focus automatically moves to the correct next page
- This component’s listeners and nodes are removed and its update API is terminal
Answer: This component’s listeners and nodes are removed and its update API is terminal. The method owns its own resources; application focus policy and garbage-collection timing are separate.
Continue this course
- Previous: JavaScript Performance Optimization Techniques
- Next: Module Bundlers: Webpack, Parcel, Vite (Overview) — Understand how bundlers work and configure them for your project
- Quick reference: JavaScript cheat sheet
Frequently asked questions
What is a reusable UI component in JavaScript?
A reusable UI component is a self-contained piece of interface — like a button, modal or card — packaged with its own markup, styling and behaviour so you can use it many times across a project without rewriting code. Reusable components make apps consistent and far easier to maintain.
How do you create reusable components in vanilla JavaScript?
You can build reusable components in plain JavaScript using functions or classes that generate and return DOM elements, Web Components (custom elements), or template literals combined with event delegation. This lesson walks through practical patterns with working examples.
Do I need a framework like React to build UI components?
No. Frameworks like React make components easier to manage at scale, but you can build reusable, dynamic components with vanilla JavaScript — and understanding how to do so makes you a stronger developer and helps you grasp what frameworks do under the hood.