Guides
Web Components
mx lives inside custom elements. The element is the public part, a real tag any page or framework can use, and mx is the private renderer that draws what's inside it.
Two ways to build with the same tools#
mx is built to live inside Web Components. mx(), dom() and render() are platform-level tools: render() is patched onto Element.prototype, so it works on any element you create, including a hand-written customElements.define'd class.
What the platform provides
- A real tag, registered with the browser
- Native lifecycle:
connectedCallback,disconnectedCallback,attributeChangedCallback - Shadow DOM, slots and form association
- Reuse from React, Vue, Angular or plain HTML
What mx provides
- Descriptions instead of
createElement/appendChild - One re-runnable
render()for first paint and updates - Rich props through
$()- objects and callbacks, not strings - The reconciler and attribute cache for cheap updates
define() (used across the rest of these docs) is the terse, mx-managed route - great for app-internal components. Registering a class extends HTMLElement is the platform route - reach for it when you want a component that HTML can author and any framework can consume, or one that takes part in forms or uses Shadow DOM. Both render with the same mx / dom / render. The rest of this guide covers the second route.
render() works on every element#
Because mx augments the prototype rather than wrapping a component class, there is nothing to extend and nothing to import. Every custom element already has render():
// mx patches Element.prototype, so render() exists on EVERY element -
// including a hand-written custom element. No define() or MX base class. ESM users import { mx } from '@tltdsh/mx' first.
class MyWidget extends HTMLElement {
connectedCallback() {
this.render( // <- Element.prototype.render
mx.h3('Hello'),
mx.p('Rendered by mx, inside a standard custom element.')
);
}
}
customElements.define('my-widget', MyWidget);class FlipCounter extends HTMLElement {
constructor() { super(); this._n = 0; } // inert - no DOM touched
connectedCallback() { this.paint(); }
paint() {
this.render(
mx.button({ onclick: _ => { this._n--; this.paint(); }, 'aria-label': 'Decrement' }, '\u2212'),
mx.span(this._n),
mx.button({ onclick: _ => { this._n++; this.paint(); }, 'aria-label': 'Increment' }, '+')
);
}
}
customElements.define('flip-counter', FlipCounter);
document.body.append(document.createElement('flip-counter'));That <flip-counter> is a fully standard custom element that you register once, inspect as itself in devtools and use from any framework, and its entire view layer is three lines of mx.
Rich props through $()#
Give the class a $() method and mx treats the element exactly like a define() component. mx.userCard(props) becomes <user-card>, the browser upgrades it to your class, and mx hands the raw props object to $(), so objects, arrays and callbacks arrive without attribute serialization.
- mx.userCardCalled with props: a description, inert data.
- <user-card>Created, then the browser upgrades it to your class.
- el.$(props)mx sees $ and hands over the props as-is.
- render()Your class paints its own children.
// A class with a $() method is an mx component: mx.userCard(props)
// creates <user-card> and calls el.$(props) with the raw object.
class MxElement extends HTMLElement {
$(props) { // null when called with no props
Object.assign(this.$state ||= {}, props);
this.update(this.$state);
return this;
}
update() {}
}
class UserCard extends MxElement {
update({ user = {}, selected = false, onselect }) {
this.render(
mx.h3(user.name),
mx.p(user.role),
mx.button({ onclick: onselect, 'aria-pressed': selected ? 'true' : 'false' },
selected ? 'Selected' : 'Select')
);
}
}
customElements.define('user-card', UserCard); // register BEFORE the first render
let people = [
{ name: 'Ada Lovelace', role: 'Mathematician' },
{ name: 'Alan Turing', role: 'Logician' }
];
let picked = 0;
let app = document.getElementById('app');
let paint = _ => app.render(...people.map((user, i) =>
mx.userCard({ user, selected: i === picked, onselect: _ => { picked = i; paint(); } })));
paint();The define() wrapper merges props into $state and renders what $() returns. A class's own $() gets neither - it receives the props and paints itself. The four-line MxElement base above does the merge once, so each component only writes update(). What mx does with an element depends on whether it has $:
| Element | Props | Children |
|---|---|---|
Has $() | Passed to $() untouched (null when there are none) and not set as attributes | Ignored - the element renders its own |
No $() | Set as attributes, but functions as properties | Reconciled into the light DOM like a plain tag, which clears anything the class painted itself |
dom.userCard(props) calls $() too and returns the element - the way to hold a reference you will call $() on later. Without a props object, dom.userCard() does not call $(), so pass {} to paint.
The inert-description trick#
This is where mx saves real work. The custom-element spec is strict about the constructor: it must not add children or attributes, and should not read them either (none are set yet). Create the element via document.createElement with a constructor that appends DOM and you get an error plus a broken HTMLUnknownElement back. So classic components leave the constructor nearly empty and build everything imperatively in connectedCallback:
// Classic custom element: the spec says the constructor must not add
// children or attributes (and should not read them - none are set yet).
// Break it and createElement reports an error and hands back a broken
// HTMLUnknownElement. So you build everything in connectedCallback:
class UserCard extends HTMLElement {
connectedCallback() {
let h = document.createElement('h3');
h.textContent = this.getAttribute('name');
let p = document.createElement('p');
p.textContent = this.getAttribute('role');
this.append(h, p); // ceremony, every time
}
}But an mx() call returns a description - plain data, not DOM. Building it adds no children or attributes to the element, so it's legal in the constructor. You can define the view up front and let connectedCallback be a single render():
// With mx, the view is a DESCRIPTION - inert data, not DOM. You can build
// it in the constructor (where DOM mutation is illegal) because it adds
// nothing to the element. connectedCallback becomes a one-liner: render it.
class UserCard extends HTMLElement {
constructor() {
super();
this._view = ({ name, role }) => // pure data, zero DOM touched
[mx.h3(name), mx.p(role)];
}
connectedCallback() {
this.render(...this._view({ name: this.getAttribute('name'), role: this.getAttribute('role') }));
}
}
customElements.define('user-card', UserCard);This class is meant to be authored in HTML, where the parser sets the attributes before connectedCallback runs. Rendered from mx.userCard({ name, role }), it is inserted first, so connectedCallback reads null, and mx then clears what it painted (see Gotchas below and Inside a render). Use dom.userCard({ name, role }) or give the class a $() when mx creates it.
The constructor's "you may not touch the DOM" rule is the single most awkward thing about authoring custom elements by hand. mx sidesteps it for free. Descriptions are inert, so "what this element looks like" can be ordinary data computed whenever you like, and the only place that actually mutates the DOM is one render() call - which is also re-runnable, so updates are the same one-liner. You stop hand-writing createElement trees and stop guarding against the constructor rules.
Reacting to attributes#
The platform's own reactivity for custom elements is observedAttributes + attributeChangedCallback. Bridge it to mx by re-rendering when an attribute changes - now the element is driven by HTML, with no JavaScript at the call site:
class StatusDot extends HTMLElement {
static get observedAttributes() { return ['state']; }
attributeChangedCallback() { if (this.isConnected) this.paint(); }
connectedCallback() { this.paint(); }
paint() {
let state = this.getAttribute('state') || 'idle';
this.render(mx.span({ class: 'dot ' + state, role: 'img', 'aria-label': state }));
}
}
customElements.define('status-dot', StatusDot);
// Now it's live from HTML, driven by attributes - no JS to wire it:
// <status-dot state="online"></status-dot>
// el.setAttribute('state', 'offline') // attributeChangedCallback -> re-renderThis is the standards-native counterpart to props. For app-internal components the $state / .$({...}) model is terser. Reach for attributeChangedCallback when the component must be authorable and controllable as plain HTML - the case for a shared, framework-agnostic element.
Attributes only carry strings. For rich data (objects, arrays, callbacks) expose a property or method on the element and call it - el.data = [...], el.$({...}) - exactly as you would with any custom element. attributeChangedCallback is for the declarative, stringly-typed surface, while properties and $() are for the rich one.
Shadow DOM and slots#
Want true style and markup encapsulation? Attach a shadow root and render into it. render() is defined on Element.prototype, and a ShadowRoot is not an Element - but it is a node container with firstChild / append, so the reconciler runs against it unchanged. Call it explicitly:
class FancyBox extends HTMLElement {
connectedCallback() {
let root = this.shadowRoot || this.attachShadow({ mode: 'open' });
// render() is an Element method; call it against the shadow root:
Element.prototype.render.call(root,
mx.style(':host{display:block;border:1px solid #4285f4;padding:12px}'),
mx.slot() // light-DOM children project here
);
}
}
customElements.define('fancy-box', FancyBox);
// Or stash the method once for ergonomics:
// root.render = Element.prototype.render; then root.render(mx.div(...))Light-DOM children the consumer passes project through mx.slot() as usual - mx renders the shadow tree and the browser does the slotting. Most apps don't need Shadow DOM (global CSS is simpler, and the light DOM is easier to style and test), but when you're shipping a widget into unknown pages, encapsulation is exactly what custom elements are for, and mx renders into it without special-casing.
Rendering into the host's light DOM (just this.render(...)) keeps your component's styles, queries and tests simple, and lets app CSS and design tokens reach in. Reach for Shadow DOM only when you specifically need isolation - distributing a widget, or guarding against host-page CSS, and don't make it the default.
Persistent references with dom()#
Inside a custom element, dom() is your tool for elements you keep and mutate directly - a list you append to, a node you hand to a third-party library, anything you'll touch after creation (the same mx() vs dom() distinction as everywhere else):
class LogView extends HTMLElement {
connectedCallback() {
this._list ||= dom.ul({ class: 'log' }); // persistent real element
this.append(this._list);
}
add(line) {
this._list.append(dom.li(line)); // keep a ref, mutate it directly
}
}
customElements.define('log-view', LogView);Build the view with mx() inside render(), and reach for dom() when you need the live node as a value. They compose freely inside a custom element exactly as they do outside one.
Where the two routes meet#
The one seam worth understanding: define() copies $ (and any other methods) onto the element when mx creates the element (via mx.tag() or dom()). An element created by the parser or by document.createElement - i.e. authored in HTML or server-rendered - does not pass through mx's creation path, so it won't have those methods unless you arrange it:
// A custom element written in HTML (or server-rendered) is created by the
// PARSER, not by mx - so it doesn't get $ or the other define() methods. Two choices:
// 1. Put the logic in the class (above) - works for any creation path.
// 2. Or keep using define(), and run a one-time upgrade pass after your
// define() calls, to attach mx's methods to parser-created elements:
document.querySelectorAll(Object.keys(components)).forEach(el =>
!el.$ && Object.assign(el, components[el.localName]));
// (See Architecture - Upgrading server-rendered custom elements.)So if a component must be authorable as HTML, either put its logic in a registered class (the platform route on this page, which the browser instantiates correctly no matter who creates it), or keep define() and run the one-line upgrade pass.
A class with $() that HTML can author
Nobody calls $() on an element the parser created, so paint the defaults from connectedCallback:
class UserBadge extends MxElement {
// Written in HTML, nobody calls $() - so paint the defaults on connect.
connectedCallback() { this.$state || this.$({}); }
update({ label = 'New' }) {
this.render(mx.span({ class: 'badge' }, label));
}
}
customElements.define('user-badge', UserBadge);
// Both work now:
// <user-badge></user-badge>
// app.render(mx.userBadge({ label: 'Beta' }))When mx renders the element into a connected parent it attaches it first and calls $(props) right after, so connectedCallback sees no $state yet and paints the defaults once before the real props arrive. dom.userBadge(props) and a render into a detached parent call $() first. Keep the defaults crash-free.
Both on one tag
The two routes compose - you can customElements.define a class and define() the same tag, getting native lifecycle plus the $() render model on one element. Give the tag one $(): if both define it, the define() one wins on elements mx creates (it is copied onto the element and shadows the class method), while parser-created elements only have the class's.
Gotchas#
app.render(mx.myWidget());
// <my-widget></my-widget> - the h3 and p are gone// insert a real node and keep it: render() places it by identity
let widget = document.createElement('my-widget');
app.render(widget);
// or give the class a $() so mx leaves its children alone:
// $() { this.paint(); return this; }app.render(mx.userCard({ user }));
// <user-card user="[object Object]">
customElements.define('user-card', UserCard);customElements.define('user-card', UserCard);
app.render(mx.userCard({ user }));
// $() receives { user }class UserCard extends HTMLElement {
// mx.userCard() -> TypeError
$({ user }) {}
}class UserCard extends HTMLElement {
$(props) {
// null is fine here
Object.assign(this.$state ||= {}, props);
// ...paint from this.$state
}
}class UserCard extends HTMLElement {
// this.render(...) now calls this method instead of the reconciler: nothing paints
render() {}
}class UserCard extends HTMLElement {
update() { this.render(mx.h3('Ada')); }
}// the button is dropped
app.render(mx.userCard({ user },
mx.button('Open')));app.render(mx.userCard({ user,
footer: mx.button('Open') }));
// update({ user, footer }) {
// this.render(mx.h3(user.name), footer);
// }The platform requires it: customElements.define('usercard', ...) throws. mx.userCard becomes <user-card> and mx.codePreview becomes <code-preview>, so a camelCase factory that starts lowercase and has at least one capital gives a valid name. Avoid the few reserved names such as font-face.
How it scales#
You can build a large application this way. A sizable production codebase can be hundreds of registered custom elements, each rendering its internals with mx, and it holds up because the division of labor is clean:
Read more: the attribute cache and upgrading server-rendered custom elements in place. The payoff is that you pay the platform's well-understood costs for structure and lifecycle, and mx's near-zero cost for rendering - rather than paying framework overhead on both.
When to take this route#
| Want | Route |
|---|---|
| A fast app-internal component | define() or a plain function |
| A component authorable in plain HTML | Registered class (or define() + upgrade pass) |
| Rich props from mx, and a real tag | Registered class with $() |
| Reuse from React / Vue / Angular | Registered class - it's just a DOM element |
| Style/markup encapsulation | Registered class + Shadow DOM |
| Native attach/detach lifecycle | Registered class (see Lifecycle) |
| Form participation | Registered class + formAssociated + ElementInternals |
| Everything else | define() - less boilerplate |
mx is there to make Web Components pleasant to write rather than to replace or compete with them. Register the element when you want what the platform offers (HTML-authorable, framework-agnostic, encapsulated, form-aware, lifecycle-driven), and render its insides with mx to skip the createElement boilerplate and keep updates cheap. The standards define the element and mx renders what's inside it.
Related: Lifecycle (connect/disconnect, and when you actually need them), upgrading server-rendered custom elements, mx() vs dom(), and methods beyond $.