Reference

Common gotchas

These are the things that trip developers up when learning mx.js. Each row shows the mistake next to the fix, followed by why it happens.

Position and identity#

mx() descriptions reconcile by position and tag, while real dom() nodes match by identity. Most list bugs come from mixing the two up. A React-style key does not change this, because mx writes it as a plain attribute.

Lists reconcile by position, not by key

Reorder an mx list and typed input values and checkbox ticks stay at the old index.
// After a sort, the input at position 0 keeps what the user typed
container.render(...items.map(i => mx.div(
    mx.span(i.name),
    mx.input({ placeholder: 'notes...' })  // ← this input doesn't move
)));
// dom() + Map: identity-stable rows
let rows = new Map;
for (let i of items) {
    let el = rows.get(i.id) ?? rows.set(i.id, dom.div()).get(i.id);
    el.render(mx.span(i.name), mx.input({ placeholder: 'notes...' }));
}
container.render(...items.map(i => rows.get(i.id)));  // nodes physically move

mx reconciles children left-to-right by tag name, not by key: on reorder the DOM nodes stay in place and only their content updates.

When render encounters a real DOM node, it matches by identity (===), not tag name. The node moves to the correct position and all internal state travels with it.

A same-tag mx() node consumes a node mx never placed

A description in front of a same-tag node you picked up from the DOM, or appended by hand, reconciles into it.
root.render(mx.div(mx.input()));   // mx creates the <div>
let row = root.firstChild;          // a handle picked up from the DOM

root.render(mx.div('Header'), row);
// row was never passed to render() as itself, so mx.div reconciles INTO it.
// Result: ONE child, the input and any typed state are gone.
let row = dom.div(dom.input());   // a real node you hold a handle to
root.render(row);                  // passed as itself: mx remembers it

root.render(mx.div('Header'), row);   // [div Header, row], input kept
root.render(mx.h2('Header'), row);    // a distinct tag is always safe

When render() places a real node, it remembers it. If a later list puts a same-tag mx() description in front of that node, the description gets a fresh element and the node keeps its content.

That protection only covers nodes a render placed as themselves. A node you took from the DOM (firstChild, querySelector) or appended by hand carries no such mark, so a same-tag description in front of it still reconciles into it. The same applies to a real node reused inside a nested description's children.

Pass the node to render() as itself once, give the sibling a different tag, or keep each list in one mode: an all-dom() list reordered by identity, or an all-mx() tree reconciled by position.

Positionally reused components keep their setup

A row that starts a timer or subscription at creation stays bound to its first datum after a sort.
// Each row polls a device on creation. After a sort, row 0's poller
// is still bound to the device it was built for - now under the wrong row.
define('device-row', {
    $({ device }) {
        this._poll ??= setInterval(() => refresh(device.id), 1000);
        return mx.span(device.name);
    }
});
container.render(...devices.map(d => mx.deviceRow({ device: d })));
// dom() + a keyed Map: each node stays bound to its own datum
let rows = this._rows ||= new Map;
for (let d of devices) {
    let el = rows.get(d.id) ?? rows.set(d.id, dom.deviceRow({ device: d })).get(d.id);
    el.$({ device: d });   // refresh this row's data without recreating it
}
container.render(...devices.map(d => rows.get(d.id)));

A component that does one-time work at creation (starts a timer, adds a listener, fetches data keyed to an id, instantiates a widget) assumes it maps to one logical item for its whole life. Inside an mx.* list that reconciles positionally by tag name, that assumption breaks: after a sort or insert, mx reuses the node at position 0 for whatever datum now sits there, but the node still carries the interval or subscription it set up for the old datum.

Rule of thumb: if a component's $ does anything at creation tied to a specific id, it must be identity-stable. Hold it in a keyed Map of dom() nodes, never a positionally-reconciled mx.* slot. Pure render-from-props rows are safe positionally, but stateful ones are not. This is the same identity rule as positional rendering, sharpened for components that set up side effects.

Merged $state travels with the reused slot too: a row rendered with { id: 1, note: 'first' } and then, after the list shrinks from the front, with { id: 2 } still holds note: 'first' (see state accumulation). Pass every key on every render, or key the rows.

render() removes children it was not given

Anything the new render call doesn't name leaves the DOM, including nodes you appended by hand.
container.render(mx.div('A'), mx.div('B'), mx.div('C'));
container.append(extra);                      // appended by hand
container.render(mx.div('A'), mx.div('B'));   // 'C' and extra are removed
let kept = dom.div('kept');
container.render(mx.div('A'), kept);
container.render(mx.div('B'), kept);   // same node in every render: it stays

This is by design. Preserve a real dom() child by including that same node in every render, or keep it in a separate container outside this renderer.

Arrays as children

A plain array passed as a child renders as a run of children, and nested arrays flatten too. You can pass a .map() result as it is or spread it with ..., and both give the same DOM.

JS
mx.ul(items.map(i => mx.li(i)));      // each li is a direct child
mx.ul(...items.map(i => mx.li(i)));   // spread: the same result
mx.ul(mx.li('first'), items.map(i => mx.li(i)), mx.li('last'));   // mixes with siblings

Flattened items follow the usual child rules: null, undefined and false are skipped, and 0 renders as text. An mx description is an array too, but it carries ._, so it stays one element and is never flattened.

Flattening recurses once per level of nesting, so an array nested a couple of thousand levels deep can run out of call stack. Code you write by hand or build with .map() stays far below that.

mx 1.4.1 and earlier stringify an unspread array into text such as "li,,a,li,,b". Spread it if your code also has to run on those versions.

Numbers leak into render

count && ... renders a literal "0", because numbers are content and only false, null and undefined are skipped.
// When items is empty, renders a literal "0" text node
container.render(items.length && mx.div('Has items'));
count && mx.span('Count: ' + count)     // renders "0" when count is 0
// Coerce to boolean: false is skipped by render()
container.render(!!items.length && mx.div('Has items'));
!!count && mx.span('Count: ' + count)   // skipped when count is 0

render() treats numbers as text nodes, so a 0 from .length is not skipped like false or null would be. Rule of thumb: if the left side of && can be a number, prefix it with !!.

Holding an mx() description where you need an element

mx.tag() returns a description array, and only dom.tag() gives you a real element with .$().
let picker = mx.colorPicker({ value: red });
picker.$({ value: blue });   // TypeError: picker.$ is not a function
let picker = dom.colorPicker({ value: red });
picker.$({ value: blue });   // works

If you need to hold a reference and call .$() on it later, use dom.tag().

dom(Component) without attrs skips $()

With no argument, dom() assumes "no attrs, no children", and a component's first $() never runs.
let picker = dom.colorPicker();   // $() never runs: the element exists but is empty
let picker = dom.colorPicker({});   // an empty attrs object triggers $()
container.render(mx.colorPicker());  // or mx() inside render(): always calls $()

dom.myComp(...) returns an element immediately. For a defined component (one with a $ function), the attrs path is what triggers the first $() call. The arg slot is overloaded: a plain object is attrs, anything else is a child. With no arg at all, dom() has no way to know you meant "attrs = {}", and picks "no attrs + no children".

Inside a render#

$() runs on every render, children reconcile before their parent's attributes, and whatever $ returns goes through render(). Each of those has an edge.

Children render before parent attributes

Inside render(), an element's children are reconciled before its own attributes are applied. This ordering is load-bearing (it's what makes .value on a <select> see its <option> children), but four consequences are observable:

  1. An event a child dispatches synchronously during its mount is missed by a parent handler from the same render description: the parent's onclick isn't attached yet. Dispatch asynchronously (setTimeout/queueMicrotask) or after mount.
  2. A child that reads a parent attribute or handler during $() sees a three-way split: one the new description dropped is already gone (null, removals are undone before the children reconcile), one it changed still shows the previous render's value, and one it added is not there yet (null, including everything on first mount). Pass data down through $state props, not by reading parent attributes.
  3. multiple and size on a <select> land after its options, so on first mount the options are selected as a single-select: only the last selected: true sticks, and a listbox (size > 1) with no selected option auto-selects option 0. A re-render fixes the multi-select, but the listbox keeps option 0 until you describe '.selectedIndex': -1. Or hold the select as a dom() node created before its options: this._s ||= dom.select({ multiple: true }); this._s.render(...options); return [this._s].
  4. A real custom element (customElements.define) rendered from a description is inserted first, so its connectedCallback runs on an empty, attribute-less element and attributeChangedCallback fires afterwards. Read attributes in attributeChangedCallback or a queueMicrotask, or build the element with dom(), which applies attributes and children before you insert it: the parser-like order.

This is intended semantics, not a bug to be fixed.

render() is not re-entrant

Re-render an ancestor synchronously from inside a child's $, and the DOM ends up a merge of an old and a new description.
// Guarded to run once, yet the outer pass resumes with its stale
// description: siblings after the kid still get the old render.
// Without the guard it recurses until the call stack overflows.
define('kid', {
    $() {
        if (!this._done) {
            this._done = 1;
            this.parentElement.$({ v: 2 });   // synchronous, inside $
        }
        return mx.b('c1');
    }
});
// Child re-renders the parent after the current pass: deferred and guarded
define('kid', {
    $() {
        let parent = this.parentElement;
        if (parent.$state.v !== 2) queueMicrotask(() => {
            if (this.isConnected && this.parentElement === parent && parent.$state.v !== 2)
                parent.$({ v: 2 });
        });
        return mx.b('c1');
    }
});

Never re-render a host synchronously from inside a child's $: this.parentElement.$(), this.$() inside your own $, or a bus emit whose listener re-renders an ancestor. The inner render walks the newer description, then the outer render resumes with its older description and finishes writing it.

Render-phase side effects that reach outside the component are the trigger. Route child-driven updates through a callback prop (see this.$({}) is a code smell) or a guarded microtask, or do it from an event handler after mount. Deferring alone loops if every render queues another change, so guard the actual state transition.

Returning a DOM node from $

A bare node falls into the spread branch, and render(...node) throws a TypeError because a node is not iterable.
define('media', {
    $({ url }) {
        return makeIframeFor(url);   // a real <iframe>: TypeError, spread syntax requires an iterable
    }
});
// Wrap in an array: render(...[node]) is fine
define('media', { $({ url }) { return [makeIframeFor(url)]; } });

// Or wrap in an mx description, so ._ takes the single-arg branch
define('media', { $({ url }) { return mx.div(makeIframeFor(url)); } });

The component wrapper dispatches the return value of $ through value._ ? render(value) : render(...value). A DOM node has no ._ property, so it falls into the spread branch, and DOM nodes are not iterable.

In practice this only matters when integrating third-party widgets (CodeMirror, charts, embeds) that hand you a real DOM element you want to mount as the component's sole child. Always wrap. The cost is one bracket pair.

Bare primitives take the same spread branch

Valid return values are a description, an array, a node inside an array, or null/false/undefined for nothing. A bare string has no ._ but is iterable, so it spreads per code point into one text node per character: return 'hello' gives five text nodes (textContent still reads hello). A number or true is not iterable and throws. 0 and '' render nothing, so return count works for 0 and throws for 1.

$() { return 'hello'; }          // 5 text nodes
$({ count }) { return count; }   // TypeError: spread syntax requires an iterable
$() { return ['hello']; }
$() { return mx.span('hello'); }
$({ count }) { return [String(count)]; }
$({ count }) { return mx.span(count); }
Why the wrapper works this way

Returning a single mx description (return mx.div(...)) is the common case, and the wrapper handles it without forcing you to write return [mx.div(...)] every time. The ._ check distinguishes "single description" from "array of children" without an Array.isArray call. DOM nodes weren't in the design space because the component itself is a DOM node: returning another one is the unusual case.

Intervals stack across re-renders

Every $() call runs your function again: clear the previous interval first.
$({ isPlaying = false }) {
    if (isPlaying) {
        this._interval = setInterval(() => tick(), 1000);   // a new one every render
    }
}
$({ isPlaying = false }) {
    clearInterval(this._interval);
    if (isPlaying) {
        this._interval = setInterval(() => tick(), 1000);
    }
}

clearInterval at the top of $(), before any conditional logic.

addEventListener in $() stacks listeners

A new closure per render adds a new listener per render. Assign the handler property, or pass a stable function.
$() {
    this.addEventListener('click', () => doStuff());   // 10 renders = 10 listeners
}
// Property assignment overwrites safely
$() {
    this.onclick = () => doStuff();
}

// Or a stable reference: addEventListener is idempotent for the same fn
let handler = () => doStuff();
$() {
    this.addEventListener('click', handler);
}

The element's attribute cache auto-cleans handlers set via render() attrs (onclick: fn), but addEventListener on this is outside that cache.

Custom events need addEventListener

onping is not a known handler property: the assignment is a plain expando and never fires.
// 'ping' is not a standard event type: a silent no-op
mx.div({ onping: e => doStuff() }, ...)
// Custom events need addEventListener, armed once
$() {
    (this.$ev ||= {}).armed ||= (this.addEventListener('ping', e => doStuff()), 1);
}

onclick: fn works because the browser registers a listener when you assign a known handler property. This is platform behavior, not an mx choice: only spec-defined on* properties (onclick, oninput, ontoggle, ...) register listeners when assigned. The addEventListener fallback is one-time: guard it so it doesn't stack (see listener stacking).

Two ways to write that latch wrong

The guard has to store a truthy value, and it must not use this._ as its name:

// addEventListener returns undefined, so the flag is never set.
// Three renders = three listeners; one dispatch fires the handler 3x.
(this._ ||= {}).armed || (this._.armed = this.addEventListener('ping', fn));

// this._ is also render()'s mx-description marker. An element carrying
// a truthy _ is destructured as [tag, attrs, kids] when passed as a
// real DOM child: TypeError: object is not iterable
root.render(mx.div(el));
// Comma operator returns 1, and $ev doesn't collide with the marker
(this.$ev ||= {}).armed ||= (this.addEventListener('ping', e => doStuff()), 1);

Any truthy sentinel and any non-_ property name will do: this.$ev, this._armed, a Set of registered types. The two rules: never let the flag be undefined, and never name the holder _ (see why ._ marks an mx description).

Mutating input arrays

Props point to the parent's data: sorting them in place changes state outside the component.
$({ items = [] }) {
    items.sort((a, b) => a.name.localeCompare(b.name));   // sorts the parent's array
}
$({ items = [] }) {
    let sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));
}

Component state#

$state is merged with Object.assign, and the definition object is copied onto every element. Both are plain JavaScript, and both surprise people.

$state accumulates: keys you don't pass persist

Each $() call merges into $state, so a key from an earlier render is still there.
el.$({ type: 'text-field', content: [] });   // render 1: set type
el.$({ content: ['tag1', 'tag2'] });          // render 2: forget to clear type

// $state is now { type: 'text-field', content: ['tag1', 'tag2'] }:
// the stale type renders a text field AND tags
// Always send complete state when switching modes
el.$({ type: null, content: ['tag1', 'tag2'] });

The destructuring defaults in $({ type = null }) document what "neutral" means for each prop. Use those values when resetting.

This includes props that make $ throw: the merge happens before your function runs, so the offending key is already in $state and a prop-less re-render throws again. Re-render with the key explicitly reset.

A parent re-passing a prop overwrites local $state

The wrapper merges props before $ runs, so a parent re-render resets what the component changed itself.
define('counter', {
    $({ count = 0 }) {
        return [
            mx.button({ onclick: () => this.$({ count: count + 1 }) }, '+'),
            mx.span(count)
        ];
    }
});

// 1. Parent: el.$({ count: 10 })  -> $state.count = 10, rendered as 10
// 2. User clicks + 5 times        -> $state.count = 15, rendered as 15
// 3. Parent re-renders same prop: el.$({ count: 10 })
//    -> Object.assign overwrites $state.count back to 10: the clicks are lost
// A different key: the prop is only a seed
define('counter', {
    $({ initial = 0 }) {
        this._count ??= initial;   // seeded once from the prop, never clobbered
        return [
            mx.button({ onclick: () => { this._count--; this.$({}); } }, '−'),
            mx.span(this._count),
            mx.button({ onclick: () => { this._count++; this.$({}); } }, '+')
        ];
    }
});
Usually this is what you want

A controlled component should accept parent-passed state. A form field whose value is owned by the parent should be overwritten when the parent re-passes. This is the declarative model doing its job.

If you need a value that survives parent re-passes, use a different key: take the prop as a seed and store local state separately, as above. That pattern needs this.$({}) to trigger a re-render, which is normally a code smell. The cleaner answer is usually to let the parent own the state and pass it down, because components that truly need local state immune to the parent are surprisingly rare.

Destructured state is a render-time snapshot

A handler closing over a destructured value reads it as of the render that created the handler.
define('counter', {
    $({ count = 0 }) {
        return [
            mx.button({ onclick: () => this.$({ count: count - 1 }) }, '−'),
            mx.span(count)
        ];
    }
});
// Live read: always sees current state, even across async gaps
onclick: () => this.$({ count: this.$state.count - 1 })

Why single clicks usually work. On a single synchronous click, the handler fires, this.$() re-renders, and a brand-new handler (closing over the fresh value) replaces the old one in the DOM before the next click. The bug is invisible until you do something slightly more interesting.

Three ways the closure goes stale

1. Multiple state updates in one handler

JSCounterexample
// Both calls read count = 5. Result is 4, not 3.
onclick: () => {
    this.$({ count: count - 1 });
    this.$({ count: count - 1 });
}

2. Async gaps

JSCounterexample
// The timeout fires with the render-time value, not the current one
onclick: () => setTimeout(() => this.$({ count: count - 1 }), 100)

3. Child-to-parent callbacks

JSCounterexample
// Parent sends count: 10, child clicks +, but the handler
// still closes over the old count from an earlier render
// when the parent re-renders without recreating the child
onclick: () => this.$({ count: count - step })

Solution 1: live read from this.$state (safest default)

Read from the live object at execution time, as in the fix above. The closure captures this (which never changes) rather than a scalar value. For handlers that survive many renders, cache them with ??= so the element's attribute cache sees the same function and skips re-attaching after the first mount:

JS
define('counter', {
    $() {
        let n = this.$state.count ??= 0;
        return [
            mx.button({
                onclick: this.dec ??= () => this.$({ count: this.$state.count - 1 })
            }, '−'),
            mx.span(n),
            mx.button({
                onclick: this.inc ??= () => this.$({ count: this.$state.count + 1 })
            }, '+')
        ];
    }
});

Solution 2: inline function with local computation

If you prefer destructuring, you can still use it safely as long as the handler is recreated every render (no caching) and you do not read the closed-over value after an async gap:

JS
define('counter', {
    $({ count = 0 }) {
        let me = this;
        return [
            mx.button({
                onclick() { me.$({ count: --count }); }
            }, '−'),
            mx.span(count),
            mx.button({
                onclick() { me.$({ count: ++count }); }
            }, '+')
        ];
    }
});

Why this works: the handler is recreated every render, so it always closes over the latest value. The parent-re-pass scenario is fine because a re-render creates a new closure with the fresh value.

Why this is less ideal: the renderer re-assigns onclick to the DOM node on every state change. V8 handles this fine in practice, but it is strictly more work than the cached-handler approach. Also, this inside a function() event handler is the DOM node (the button), not the component. You must capture the component in a local variable (let me = this) or use an arrow function.

Solution 3: batch multiple mutations into one this.$() call

If you are mutating the same value several times before re-rendering, compute locally and call this.$() once. It is faster (a single render pass) and sidesteps the stale-read problem for the duration of the handler:

// Two renders; the second reads a stale closure
onclick: () => {
    this.$({ count: count - 1 });
    this.$({ count: count - 1 });
}
// One render; the local variable is authoritative for this event
onclick() {
    let c = count;
    c -= 2;
    me.$({ count: c });
}
Which pattern to use when
  • Live read + cached handler: best for stateful components with many re-renders. Most efficient, always correct.
  • Destructured + inline handler: fine for simple components with minimal re-renders where re-attachment overhead is negligible. Avoid async gaps.
  • Batch updates: always do this when you need to change the same key multiple times before re-rendering.
The common mistake

Most developers write the first pattern (() => this.$({ count: count - 1 })) because it looks clean and works in the toy example. It only breaks later, when someone adds a debounce, a confirmation dialog, or a second increment. Start with the live-read pattern and you never have to debug it.

Definition-object properties are shared by reference

define() copies the definition onto every element without cloning: a mutable value becomes one value shared by every instance.
// Every <expand-row> shares ONE $state object and ONE items array
define('expand-row', {
    $state: { open: false },
    items: [],
    $({ open = false }) {
        return mx.span(open ? '▾' : '▸');
    }
});

let a = dom.expandRow({}), b = dom.expandRow({});
a.$state === b.$state    // true
a.items === b.items      // true

a.$({ open: true });
b.$state.open            // true - b never asked for this
// Per-instance: the ??= runs against this element's own $state
define('expand-row', {
    $({ open }) {
        this.$state.open ??= false;
        this._seen ||= new Set;          // private, per-instance
        return mx.span(this.$state.open ? '▾' : '▸');
    }
});

// Or just take it as a prop with a destructuring default
define('expand-row', {
    $({ open = false }) { return mx.span(open ? '▾' : '▸'); }
});

define(name, obj) stores obj once and does Object.assign(element, obj) on every element it creates, copying every property by reference.

Nothing crashes and nothing warns. The second row simply shows the first row's data the next time anything re-renders it, and a push into this.items from one instance appears in all of them. It looks like a reconciler bug, but it is Object.assign doing exactly what it says. Anything per-instance has to be created during $(), where this is the element.

Immutable primitives on the definition object are fine: rowHeight: 48 is shared too, but sharing a number nobody reassigns is harmless. The rule is only about values you mutate.

The copy happens once, at element creation. Calling define() again with the same name replaces components[name] but leaves every existing host on the definition it was created with: new siblings get the new $, reused ones keep the old. To migrate a live host, Object.assign(host, components[name]) or replace it.

Getters and setters don't survive either

Object.assign reads each source property and writes a plain data property. An accessor on a definition object is flattened into a one-time snapshot, computed at element-creation time with this bound to the definition object (not the element), and its setter is discarded entirely:

JSCounterexample
define('bad-accessor', {
    get tagUpper() { return String(this.localName).toUpperCase(); },
    set thing(v) { this._got = v; },
    $() { return mx.span('x'); }
});

let el = dom.badAccessor({});
el.tagUpper            // "UNDEFINED" - this.localName was read off the plain object
el.thing = 42;
el._got                // undefined - the setter is gone, 42 just overwrote a data property

Use a plain method and call it (el.tagUpper()), or compute the value inside $. Accessors that must live on the element need Object.defineProperty inside $.

Neither do prototype methods: Object.assign copies own enumerable properties only, so define(name, new SomeClass) leaves this.helper() undefined and the first render throws. Pass an object literal.

this.$({}) is a code smell#

Flushing hidden mutations with this.$({})

An empty merge re-runs $ with unchanged state, so whatever actually changed is invisible.
add(item) {
    this._items.push(item);       // mutation nobody sees
    this.$({});                   // "please re-render"
}
// Make the change part of state
$({ items = [] }) {
    return mx.button({ onclick: () =>
        this.$({ items: [...items, newItem] })
    }, 'Add');
}

Calling this.$({}) merges nothing into $state and re-invokes $ with unchanged state. If you find yourself writing it, the component is almost always relying on this._x mutations as side effects and using $({}) to flush a render.

If the re-render is triggered by a child callback, have the child call onChange/onSelect/etc. and let the parent re-render with meaningful state. See $state vs this._property for the full rule.

Attributes and events#

mx writes attributes with setAttribute and events as native handler properties. There is no translation layer, so the platform's rules apply as-is.

React-style names don't work

mx uses native DOM names, so onClick never fires. Always use lowercase.
mx.button({ onClick: handler })   // React convention: never fires
mx.button({ onclick: handler })   // the standard DOM event name

Three common React conventions fail silently:

ReactDOM / mxFailure mode
onClickonclickHandler never fires (property name mismatch)
classNameclasssetAttribute creates a nonstandard "classname" attribute that CSS selectors don't match
htmlForforLabel-input association broken

The same rule holds for every HTML attribute and event: use lowercase, never camelCase. tabIndex happens to work, because setAttribute lowercases HTML attribute names, but tabindex is the canonical form. SVG attributes are case-sensitive, so they keep their spec casing (viewBox, preserveAspectRatio).

Boolean attributes use HTML truthiness, not JS

Only null, undefined and false remove an attribute, but 0, NaN, "" and "false" all set it.
// All of these set the attribute. The button ends up disabled:
mx.button({ disabled: 0 })           // setAttribute('disabled', '0')
mx.button({ disabled: NaN })         // setAttribute('disabled', 'NaN')
mx.button({ disabled: '' })          // setAttribute('disabled', '')
mx.button({ disabled: 'no' })        // setAttribute('disabled', 'no')
mx.button({ disabled: 'false' })     // setAttribute('disabled', 'false')
// Coerce to a strict boolean first
mx.button({ disabled: !!errorCount })         // 0 -> false -> removed
mx.button({ disabled: state === 'sending' })  // boolean output
mx.button({ disabled: missing || false })     // default to false
mx.button({ disabled: cond ? true : null })   // explicit two-state

mx's attribute setter treats exactly three values as removal triggers:

JS
mx.button({ disabled: false })       // removeAttribute('disabled')
mx.button({ disabled: null })        // removeAttribute('disabled')
mx.button({ disabled: undefined })   // removeAttribute('disabled')
Why?

HTML boolean attributes are presence-based, not value-based. <button disabled>, <button disabled=""> and <button disabled="false"> all render the same disabled button. The browser doesn't parse the value. The attribute either exists or it doesn't.

mx mirrors the platform. Treating 0 or "" as "remove" would silently corrupt non-boolean attributes that need those values: padding: 0, flex: 0, value: '', placeholder: '', tabindex: 0 are all real and meaningful. Only the JS nullish pair plus literal false is unambiguous as "the attribute is absent".

Or use the literal true value, which mx serializes to the string "true" on every path (mx, dom, $attrs): disabled: true gives disabled="true". The attribute is present, so boolean attributes activate. Enumerated attributes like aria-expanded get "true" from true, but false removes the attribute, so pass String(value) when you need "false" (see boolean ARIA values).

No built-in class or style helpers

Arrays and objects are stringified by setAttribute: class="a,b", style="[object Object]".
mx.div({ class: ['a', 'b'] })                  // class="a,b" (one class named "a,b")
mx.div({ class: { foo: true, bar: false } })   // class="[object Object]"
mx.div({ style: { color: 'red' } })            // invalid CSS, dropped silently
mx.div({ class: 'a b' })
mx.div({ class: cond ? 'foo active' : 'foo' })
mx.div({ style: `color:${color};width:${w}px` })

Other frameworks accept arrays, objects and conditional maps for class and style. mx passes both to setAttribute, which converts the value to a string.

Why no helpers?

mx is under 1 KB brotli. A clsx-style class composer would add ~150 B, which is meaningful at this scale. The bigger reason is that components decide their own classes inside $. The pattern that motivates class={a:true,b:isOn} (per-render conditional class flipping at the call site) is rare in practice. Most apps swap one or two states (active, disabled, loading) that destructure cleanly into a template literal.

If you really do need object-style class composition, a few lines of plain JS do it. Object.entries() turns each object into key-value pairs that you can filter and join. Keep them in your own utils:

JS
// Drop into your own utils.js
let cls = (...args) => args.flat().filter(Boolean).map(a =>
    a.constructor === Object
        ? Object.entries(a).filter(([,v]) => v).map(([k]) => k).join(' ')
        : a
).join(' ');

mx.div({ class: cls('btn', size, { active, disabled }) });

The same lesson applies beyond classes. mx ships the smallest set of primitives that compose. Things you'd only use in 5% of components belong in your project, not in the framework.

Style: prefer .style inside $

If you're already inside a component, skip the attribute path entirely. Direct property writes are faster than setAttribute and accept structured input:

JSFragment
$({ color, hidden }) {
    this.style.cssText = 'padding:8px';   // batch many at once (replaces all inline styles)
    this.style.color = color;             // direct property
    if (hidden) this.style.display = 'none';
    return [...];
}

One form per key: name or .name, never both

title and '.title' address one slot, so naming both leaves a stale value behind.
mx.div({ title: 'a', '.title': 'b' })   // title="b"
mx.div({ title: 'a' })                   // still title="b" - 'a' is never re-asserted
mx.div({ title: 'a' })
mx.div({ '.title': 'b' })

For a reflected attribute, title and '.title' address the same DOM slot. On first render the later key wins, and when the '.title' form is later dropped the stale b stays: the plain title is a hit in the element's attribute cache, so a is never re-asserted.

Flipping the same key from one form to the other across renders is fine: { '.onclick': fn } followed by { onclick: null } detaches the handler correctly. The hazard is only both forms in the same description.

Dropping value on a <select> deselects everything

A dropped or null value clears the property to '': selectedIndex -1, not the first option.
define('picker', {
    $({ v = null }) {
        return mx.select({ value: v }, mx.option({ value: 'a' }, 'A'), mx.option({ value: 'b' }, 'B'));
    }
});
el.$({ v: 'b' });      // B selected
el.$({ v: null });     // selectedIndex -1, no option selected
// Describe the default you want
mx.select({ value: v || 'a' }, ...options)
mx.select({ '.selectedIndex': 0 }, ...options)

// Or give a blank state a placeholder the drop lands on
mx.select({ value: v }, mx.option({ value: '' }, 'Pick one'), ...options)

value is dual-tracked by render(), and dropping a dual-tracked key (or passing null) clears the property to ''. On a <select> with no option whose value is '', select.value = '' is the platform's own no-selection state. That is the faithful "no value described" state, not a reset to the first option.

That is the result with an unchanged option list. If the same render also inserts or removes options, the browser's selectedness reset lands on the first option (a here), where a fresh <select> would land too. Or use '.value', which is not dual-tracked, if the user's choice should survive the drop.

Null-prototype objects aren't attrs

Object.create(null) fails the attrs check, lands in the child slot, and rendering it throws.
let attrs = Object.create(null);
attrs.class = 'box';

// attrs is treated as a child, and turning it into text throws:
//    TypeError: Cannot convert object to primitive value
mx.div(attrs, 'content')
// Plain object literals work
mx.div({ class: 'box' }, 'content')

mx detects attrs via attrs.__proto__ === Object.prototype. A null-prototype object fails that check, and has no toString for the DOM to stringify.

It's rare in practice, but worth knowing if you're building attrs programmatically. Object literals you write by hand always pass, including literals with an own constructor key, which were misclassified as children before mx 1.3.2.

The silent version: parsed JSON with an own __proto__ key

The check reads the __proto__ property, and JSON.parse creates own data properties, including one named __proto__. Such an object still has Object.prototype as its real prototype, but the property read returns the own value, so mx's check fails. Nothing throws and nothing warns: the object lands in the child slot, every attribute is silently dropped, and it renders as the text [object Object].

let attrs = JSON.parse('{"__proto__": {}, "class": "box"}');

Object.getPrototypeOf(attrs) === Object.prototype   // true
attrs.__proto__ === Object.prototype                // false ← the check mx makes

// Renders <div>[object Object]content</div>, class never applied
mx.div(attrs, 'content')
// Drop the key before using the object as attrs
delete attrs.__proto__;
mx.div(attrs, 'content')   // <div class="box">content</div>

Copying doesn't help: { ...attrs } re-creates the own __proto__ data property, and Object.assign({}, attrs) goes through the __proto__ setter, which reassigns the target's prototype and fails the check for a second reason. delete, or rebuilding key-by-key while skipping __proto__, are the fixes. It's only a concern when attrs come from JSON you don't control.

Global ids inside components

Two instances means two elements with one id: which one does getElementById return?
$() {
    return mx.input({ id: 'search' });
}
// Later: document.getElementById('search')   // which one?
$() {
    return mx.input({ class: 'search' });
}
// Later: this.querySelector('.search')

Query within the component's own DOM tree instead.

Don't drive logic off rendered text

Comparing textContent couples logic to display copy, so a relabel or a translation breaks it silently.
// Breaks when 'Active' becomes 'active', 'Enabled', or 'Aktiv'
if (row.querySelector('.status').textContent === 'Active') {
    enable();
}
// Read from state, or a data attribute that never gets translated
if (row.dataset.status === 'active') {
    enable();
}

Rendered text is for humans, so keep the machine-readable truth in your state object or a data-* attribute. The display string should be derived from state, never be the source of it.

Names, tags and the proxy#

mx.fooBar becomes the tag foo-bar through a Proxy that answers every key. The conversion and the Proxy each have a few sharp corners.

PascalCase produces a leading hyphen

The camelCase-to-kebab conversion has no anchor: MyWidget becomes -my-widget, and creating that element throws InvalidCharacterError in Chromium.
mx.MyWidget()      // tag '-my-widget': render() throws InvalidCharacterError
dom.ColorPicker()  // throws InvalidCharacterError right away (Chromium)
define('MyWidget', { $() {...} });   // no error: stored as '-my-widget'
mx.myWidget()      // <my-widget>
dom.colorPicker()  // <color-picker>

// Or use the string form directly
mx('my-widget')
dom('color-picker')

The conversion uses /[A-Z]/g with no anchor. A leading capital produces a leading hyphen, which is not a valid element name: createElement() throws InvalidCharacterError in Chromium when the element is rendered. define() applies the same conversion as the call sites, so camelCase and kebab-case names always match up:

JSFragment
// Both stored as 'my-widget'; mx.myWidget() finds them
define('myWidget', { $() {...} });
define('my-widget', { $() {...} });
Why camelCase, not PascalCase?

JavaScript's informal convention reserves PascalCase for things you call with new (constructors, classes) and camelCase for everything else. mx.myWidget is a function call, not a constructor invocation: it returns an array, not a fresh instance via new. So the call site reads as camelCase by convention.

If you really want PascalCase identifiers (say, mirroring JSX-style component naming), declare a plain function instead: let MyWidget = (props, kids) => mx.div(...). Functions are callable identifiers, so the casing convention is yours to break. define()-components map to DOM tags, and DOM tags are kebab-case, which is what camelCase converts to cleanly.

Reserved property names: $, render, $attrs

mx puts render and $attrs on Element.prototype, and reads $ to tell a component from a plain element. A <form> exposes every descendant control by name or id as an own property that shadows the prototype, so a control named $, render or $attrs turns form.$ into the <input>. The first mount succeeds, but the second render reads form.$ to decide whether the form is a component and throws is not a function. The same getter shadows the DOM methods the engine calls on a <form> (setAttribute, removeAttribute, removeChild, insertBefore), so a control named insertBefore breaks rendering children into that form. This is how the DOM works: it bites any library that calls methods on a form. Never use any of those names on a form control:

// Mounts fine, throws on the next render of the same parent
mx.form(mx.input({ name: '$' }))
mx.form(mx.button({ id: 'render' }))
// Any other name
mx.form(mx.input({ name: 'query' }))

Why ._ marks an mx description

render() has to distinguish four things in its argument list: an mx description (mx.div(...)), a real DOM node, a plain array, and anything else (text content, nullish). A description is an array too, so the first check is a single property read, value._:

JS
// Inside render(), simplified:
if (value._)             { /* mx description: [tag, attrs, kids] */ }
else if (value.nodeType) { /* a real DOM node */ }
else if (value.pop)      { /* plain array: flattened into the list */ }
else                     { /* text content, or skip if null/false */ }

There are three reasons for choosing _ specifically, and they're all just JavaScript:

  • Compression. Brotli's dictionary already contains ._ from minified JS everywhere on the web. The marker costs essentially zero compressed bytes, much cheaper than .__mx or a Symbol.
  • Uniqueness. Real-world data objects almost never have a top-level _ key. App data uses semantic names (id, name, value). The collision surface is tiny.
  • Speed. A property lookup and truthy test is one of the cheapest operations in V8, faster than Array.isArray, instanceof or symbol checks. render() runs this on every child of every render, so the per-call cost matters.
The collision surface

If you pass a plain object whose _ field is truthy as a child, render() destructures it as [tag, attrs, kids] and either crashes or mis-renders. This is rare in practice (data fetched from APIs typically uses semantic keys), but worth knowing if you build render arguments from foreign data:

let data = { _: 'metadata', name: 'Alice' };
root.render(data);   // this child collides with the descriptor marker
// Stringify, project the field, or wrap explicitly
mx.div(JSON.stringify(data));
mx.div(mx.span(data.name));

Never await the mx or dom proxy itself

The proxy answers every key, including then, so it looks like a promise that never settles.
typeof mx.then          // "function" ← mx looks like a promise

await mx                // hangs forever, no error
Promise.resolve(dom)    // never settles
await Promise.all([mx]) // hangs the whole batch
// A description is a plain array: awaiting alongside it is fine
await Promise.all([mx.div('a'), fetchThing()])

mx and dom are Proxy objects whose get trap answers every key with a bound tag factory. There is no allow-list of real HTML tags. That includes then, the one property name the language treats as special: anything with a callable then is a thenable, and the promise machinery will call it and wait to be resolved. The factory just builds a <then> description and ignores the callbacks, so the promise never settles.

Only the bare proxy is affected. In practice: don't return mx or dom from an async function, don't put them in a Promise.all array, and don't hand them to a generic helper that might await its argument.

Related: string coercion throws

The same unconditional trap means symbol keys reach the kebab-caser, which calls .replace on them. So String(mx) and `${mx}` throw a TypeError (.replace is not a function), and [].concat(mx) silently returns []. Logging the proxy with console.log(mx) is safe, but interpolating it into a string is not.

Both faces are fixable with a guarded get trap, but the guard costs more bytes than the hazard is worth at this size, so it is documented rather than fixed. You will not hit either one by writing ordinary mx code.

The tag-name cache is permanent

mx memoizes its camelCase-to-kebab-case conversion in a plain module-level object:

JS
let tagCacheObject = {},
    toTag = tagAlias => tagCacheObject[tagAlias] ||= tagAlias.replace(/[A-Z]/g, '-$&').toLowerCase();

Every unique tag name you ever pass to mx.* or dom.* lives in this object until the page closes. There is no eviction. This is by design.

Why this is fine

A real app uses a bounded number of tag names: div, span, button, input, plus your custom components. That's maybe 60 unique strings in total. The cache occupies a few hundred bytes for the lifetime of the tab, and skipping the regex on every call is a meaningful win at 60fps.

This is just how JS works: any object reachable from a closure (or the global scope) is retained until that closure is unreachable. The cache is reachable from the mx Proxy, which is global and lives until the page unloads. The same is true of every cache, registry, or memo your app builds.

When it would matter

If you generate tag names dynamically from unbounded input, the cache grows without bound:

// One new entry per id, forever
items.forEach(item => mx(`row-${item.id}`, ...));
// A fixed tag, distinguished by attribute
items.forEach(item => mx('list-row', { 'data-id': item.id }, ...));

This is rare, since most apps use a fixed set of tag names, but it's the kind of leak that's invisible until your tab has been open for a week. More generally, any cache keyed on user data without an eviction policy is a memory leak waiting for the right input.

SVG#

SVG elements are created in the SVG namespace when they sit inside an svg host, but tag names still go through the kebab-caser and attributes through plain setAttribute.

Case-sensitive SVG elements get kebab-cased

mx.clipPath() becomes <clip-path>, which SVG ignores, so the subtree silently renders nothing.
// Becomes <clip-path>: not a real SVG element, silently inert
mx.svg(mx.clipPath({ id: 'c' }, mx.rect({ width: 10, height: 10 })))
// Create case-sensitive elements directly, include by identity
let clip = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath');
clip.$attrs({ id: 'c' }).render(mx.rect({ width: 10, height: 10 }));
root.render(mx.svg(clip));

The affected elements are the handful whose tag names are case-sensitive: linearGradient, radialGradient, clipPath, foreignObject, textPath, animateTransform and the fe* filter primitives. Lowercase SVG tags (svg, path, circle, rect, g, defs, mask, use, ...) work normally.

For foreignObject specifically, half the trap is gone: since mx 1.3.2, children rendered into a foreignObject host are created back in the HTML namespace, so fo.render(mx.div(...)) displays normally. (Before the fix they inherited the SVG namespace and rendered invisibly.) The foreignObject element itself is case-sensitive and still needs createElementNS, like everything else in this list.

Components inside <svg> are plain SVG elements

Nested in an svg host, a component tag is created in the SVG namespace, so $ never runs and props become attributes.
// Inert: <my-widget> becomes an SVG-namespaced element, $ never runs
root.render(mx.svg({ width: 40 }, mx.myWidget({ n: 1 })));
// The component owns the svg
define('my-widget', { $({ n }) { return mx.svg({ width: 40 }, mx.circle({ r: n })); } });

// Or host HTML-namespace content in a foreignObject
let fo = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
fo.render(mx.myWidget({ n: 1 }));
root.render(mx.svg({ width: 40 }, fo));

The registry is never consulted: the children are created as inert SVG-namespace nodes, and the props are written as plain attributes (<my-widget n="1">). Nothing throws.

This is not an engine choice to revisit: an unknown-tag element inside <svg> is non-rendering in every browser, in either namespace, so a component host cannot live in SVG content at all. Return the svg from the component, compose the SVG from plain descriptions or dom() nodes, or render into a foreignObject host, where components work normally.

Namespaced SVG attributes are ignored

Attributes go through plain setAttribute, so xlink:href lands in the wrong namespace and no-ops.
// Older SVG that uses xlink: this no-ops
mx.use({ 'xlink:href': '#icon-star' })
// Modern SVG (SVG 2, in every browser since ~2017)
mx.use({ href: '#icon-star' })

mx creates SVG elements via createElementNS: mx.svg is always created in the SVG namespace, while mx.path, mx.circle and the rest inherit it only when nested inside an svg host, since the namespace is taken from the host element. A top-level mx.path or any dom.path/dom.circle lands in the HTML namespace and renders invisibly. Attributes are set via plain setAttribute, not setAttributeNS, so xlink:href, xml:space and xml:lang land in the wrong namespace and the browser silently ignores them.

Why no support?

SVG 2 deprecated the xlink: namespace in 2017. Every major browser supports unprefixed href on SVG elements: Chrome 49+, Firefox 51+, Safari 12+, Edge 79+. If you're not targeting IE11 or pre-2018 Safari, you don't need xlink:.

mx omits the namespace path because the byte cost (~80 B compressed for a parallel setAttributeNS branch) buys compatibility with software that no longer ships security patches. Check whether your real constraint is browser support or markup copied from an old tutorial. Usually it is the markup, and the fix is updating the markup, not the framework.

If you really do need it

Drop into the underlying DOM API directly inside $:

JS
define('legacy-svg-icon', {
    $({ iconId }) {
        let use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
        use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#' + iconId);
        return mx.svg(use);
    }
});

The two-line escape hatch is always available. mx doesn't hide the platform but just declines to ship a wrapper for an attribute path the platform itself has retired.