Build an Accessible Web Component in 60 Lines With Zero Build Step and Headless Behaviors
Most UI libraries give you a fixed set of components. Eventually your app needs a custom widget that is not in the catalog, and you end up rewriting pointer handling, Escape key dismissal, ARIA attributes, dark mode, mob
Most UI libraries give you a fixed set of components. Eventually your app needs a custom widget that is not in the catalog, and you end up rewriting pointer handling, Escape key dismissal, ARIA attributes, dark mode, mobile hover guards, and event cleanup by hand.
In @wcomp/elementum (v0.9.0), the same base class, micro-signals, and headless behaviors that power all 115 built-in elements are exported directly so you can build your own components in one file with zero build step.
Here is a complete <my-action-panel> component in plain ES module JavaScript.
1. The component
import { Elementum, html, css, signal } from '@wcomp/elementum';
import {
createPressBehavior,
createDisclosureBehavior,
createDismissableLayer,
triggerHaptic,
announce,
} from '@wcomp/elementum/behaviors';
export class MyActionPanel extends Elementum {
static observedAttributes = ['label', 'disabled', 'open', 'haptic'];
label = signal('Actions');
disabled = signal(false);
open = signal(false);
static styles = css`
:host {
display: inline-block;
position: relative;
font-family: var(--el-font-sans, system-ui, sans-serif);
}
button {
padding: 8px 14px;
border-radius: var(--el-radius-md, 8px);
border: 1px solid var(--el-surface-border, #e2e8f0);
background: var(--el-surface-card, #ffffff);
color: var(--el-text-primary, #0f172a);
cursor: pointer;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
outline: none;
transition: background-color 150ms ease, transform 100ms ease;
}
button:focus-visible {
box-shadow: 0 0 0 3px var(--el-focus-ring, rgba(37, 99, 235, 0.4));
}
:host([data-pressed]) button {
transform: scale(0.97);
}
@media (hover: hover) and (pointer: fine) {
button:not([disabled]):hover {
background: var(--el-surface-muted, #f3f4f6);
}
}
@media (prefers-reduced-motion: reduce) {
button {
transition: none;
}
:host([data-pressed]) button {
transform: none;
}
}
.panel {
margin-top: 8px;
padding: 12px;
border-radius: var(--el-radius-md, 8px);
border: 1px solid var(--el-surface-border, #e2e8f0);
background: var(--el-surface-elevated, #ffffff);
color: var(--el-text-primary, #0f172a);
}
`;
attributeChanged(name, _oldVal, newVal) {
if (name === 'label') this.label.value = newVal || 'Actions';
if (name === 'disabled') this.disabled.value = this.boolAttr('disabled');
if (name === 'open') this.open.value = this.boolAttr('open');
return true;
}
rendered() {
const trigger = this.root.querySelector('button');
const panel = this.root.querySelector('.panel');
createPressBehavior(this, trigger, {
isDisabled: () => this.disabled.value,
signal: this.signal,
});
const disclosure = createDisclosureBehavior(trigger, panel, {
initialOpen: this.open.value,
signal: this.signal,
onOpenChange: (isOpen) => {
if (this.boolAttr('haptic')) triggerHaptic();
this.open.value = isOpen;
this.setHostState('open', isOpen);
this.emit(isOpen ? 'open' : 'close', { open: isOpen });
announce(isOpen ? 'Panel opened' : 'Panel closed');
},
});
createDismissableLayer(this, {
isOpen: () => this.open.value,
onDismiss: () => disclosure.close(),
signal: this.signal,
});
}
render() {
return html`
<button type="button" part="trigger" ?disabled=${() => this.disabled.value}>
${() => this.label.value}
</button>
<div class="panel" part="panel">
<slot></slot>
</div>
`;
}
}
if (!customElements.get('my-action-panel')) {
customElements.define('my-action-panel', MyActionPanel);
}
2. Five patterns doing the heavy lifting
-
Fine-grained bindings with arrow functions. Writing
${() => this.label.value}insidehtmlupdates only that text node whenlabelchanges. The Shadow DOM does not re-render. Outside a component, you can also usebindAttr,bindClass, andbindTextfrom@wcomp/elementumfor surgical DOM updates in vanilla JS. -
Automatic cleanup via
this.signal. EveryElementuminstance provides anAbortSignalthat aborts indisconnectedCallback(). Passingsignal: this.signaltocreatePressBehavior,createDisclosureBehavior, andcreateDismissableLayerremoves every listener on unmount with zero manual teardown code. -
Predictable light and dark mode with layered tokens. Using
--el-surface-card,--el-surface-elevated,--el-text-primary,--el-color-primary-text, and--el-focus-ringmakes the component follow<html data-theme="dark">across Chromium, Firefox, and Safari. Default tokens live inside@layer elementum.tokens, so app-level overrides win without!important. -
Mobile-first interaction defaults. Gating
:hoverinside@media (hover: hover) and (pointer: fine)prevents sticky hover states on touchscreens,touch-action: manipulationremoves tap delay, andtriggerHaptic()adds coarse-pointer vibration that skips desktop andprefers-reduced-motion: reduce. -
Standard DOM events and framework interop.
this.emit('open', { open: true })dispatches a bubbling, composedCustomEvent, soaddEventListener, React 18 and 19, Vue 3, Svelte 5, and Angular 19+ all receive it.
3. Adding native form participation
If your custom element is a form control, add static formAssociated = true and call this.setFormValue(val) when the value changes. The base class handles el.form, bidirectional .checked, .value, and .disabled property reflection, <button type="reset"> via formResetCallback() (restoring defaultChecked and defaultValue captured on first connect), <fieldset disabled> via formDisabledCallback(), and ElementInternals validity checks.
4. Try it live in StackBlitz
You can edit my-action-panel.js, toggle light and dark mode, and test Escape dismissal live in StackBlitz with zero setup:
- Open in StackBlitz: https://stackblitz.com/github/pinguxx/Elementum/tree/main/examples/custom-component-demo?file=my-action-panel.js
- Live hosted demo: https://elementum-sage.vercel.app/examples/custom-component-demo/
5. Verify your markup before shipping
Run npx @wcomp/elementum check locally (or call lint_accessibility on the hosted MCP server at https://elementum-sage.vercel.app/mcp) to catch missing labels, transition: all, scale(0), bare 100vh, hardcoded hex colors, and common API mistakes automatically.
- Full authoring guide: https://github.com/pinguxx/Elementum/blob/main/docs/authoring-components.md
- Live component catalog (115 elements): https://elementum-sage.vercel.app/examples/index.html
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.