Reference

Cheat sheet

The whole API, the attribute rules and the idioms on one page. Every snippet is a fragment: copy it into a component, not a blank file.

API#

The API is four globals and two element methods, plus $() and $state on component elements. Each badge shows the return value.

mx(tag, attrs?, ...children)Element description for render()Arraymx.tag(attrs?, ...children)Shorthand via ProxyArraydom(tag, attrs?, ...children)Create a real DOM elementHTMLElementdom.tag(attrs?, ...children)Shorthand via ProxyHTMLElementdefine(name, { $, ... })Register a componentvoidcomponentsComponent registryobjectel.render(...nodes)Reconcile children into the elementthisel.$attrs(attrs)Batch-set attributes and propertiesthisel.$(props?)Update component state and re-renderthisel.$statePersistent state across rendersobjectFull API reference

Attributes#

SyntaxBehaviorExample
name: 'value'setAttributeclass: 'active'
'.name': valueel[name] = value'.value': text
name: nullremoveAttributedisabled: null
name: falseremoveAttributehidden: false
name: truesetAttribute(name, 'true')disabled: true
key: fnel[key] = fn (any function)onclick: handler
value / checked / selectedIn render(): attribute + propertyvalue: text

render() rules#

InputBehavior
mx.tag(...)Create or reuse by tag name, update attrs, recurse into children
Real DOM nodeIdentity match by reference: same node is a no-op, a different one moves
String / NumberCreate or update a text node (numbers auto-cast)
Plain arrayFlattened into the child list, nested arrays too (mx 1.4.1 and earlier: spread it)
null / undefined / falseSkipped: use it for conditional rendering

Excess old children are removed. render() returns this for chaining.

Component#

The method shorthand and destructured parameters here are ordinary JavaScript.

JSFragment
define('my-thing', {
    $({ label = '', count = 0, onclick }) {
        return [
            mx.span(label),
            mx.span(count),
            mx.button({ onclick }, '+')
        ];
    }
});

// Use
container.render(mx('my-thing', { label: 'Clicks', onclick: () => ... }));

// Update
el.$({ count: 5 });

State#

JSFragment
// Props merge into $state automatically
$({ count = 0 }) {
    // this.$state === the argument object
    // Parent: el.$({ count: 5 })  →  count = 5
    // Self:   this.$({ count: count + 1 })  →  re-renders

    // Private cache (not in $state)
    this._rowMap ||= new Map;
}

Events#

JSFragment
// On children - property in attrs
mx.button({ onclick: () => this.$({ count: count + 1 }) }, '+')

// On component root - direct assignment
this.onclick = () => navigation.navigate('/page');

// Callback props
$({ onchange }) {
    mx.input({ oninput: e => onchange?.(e.target.value) })
}

// Event bus (your own small helper, not part of mx: see /architecture)
events.send('asset:select', id);
let off = events.on('asset:select', id => updateAll());   // off() unsubscribes

Conditional rendering#

Use JavaScript's logical AND or conditional operator to choose a child.

JSFragment
// Short-circuit (preferred)
isOpen && mx.div('Content')
hasItems && mx.ul(...items.map(i => mx.li(i.name)))
showBtn && mx.button('Click')

// Ternary (when you need an else branch)
isLoading ? mx('spinner') : mx.div('Loaded')

// In arrays - null / false skipped (0 renders as text)
return [
    mx.h1('Title'),
    showBtn && mx.button('Click'),
    mx.p('Footer')
];

Lists#

map() transforms each item, and spread syntax passes the results as children.

JSFragment
// Simple - fresh descriptions each render
mx.ul(...items.map(item => mx.li(item.name)))

// Keyed - persistent DOM for stateful rows
this._rowMap ||= new Map;
for (let [id] of this._rowMap)
    if (!data.find(d => d.id === id)) this._rowMap.delete(id);   // drop rows no longer in data
for (let d of data) {
    let el = this._rowMap.get(d.id) ?? this._rowMap.set(d.id, dom('my-row')).get(d.id);
    el.$({ data: d });
}
container.render(...data.map(d => this._rowMap.get(d.id)));

Forms#

JSFragment
// Input binding
mx.input({
    value: name,
    oninput: e => this.$({ name: e.target.value })
})

// Checkbox
mx.input({
    type: 'checkbox',
    checked: isActive,
    onchange: e => this.$({ isActive: e.target.checked })
})

// Form submit
mx.form({ onsubmit: e => {
    e.preventDefault();
    // handle submission
}}, ...fields)

SVG#

JSFragment
// Auto-detects SVG namespace
mx.svg({ viewBox: '0 0 24 24', width: 20, height: 20 },
    mx.path({ d: 'M12 2L2 7l10 5 10-5z', fill: 'none',
        stroke: 'currentColor', 'stroke-width': '2' })
)

// Sparkline
let pts = data.map((v, i) =>
    (i / (data.length - 1) * w).toFixed(1) + ',' +
    (h - (v - min) / range * h).toFixed(1)
).join(' ');
mx.svg({ viewBox: '0 0 ' + w + ' ' + h },
    mx.polyline({ points: pts, fill: 'none', stroke: color })
)

Timers & intervals#

JSFragment
$({ isPlaying = false }) {
    clearInterval(this._interval);  // always clear first

    if (isPlaying) {
        this._interval = setInterval(() => {
            this.$({ progress: (this.$state.progress || 0) + 1 });
        }, 1000);
    }
}

Class binding#

filter(Boolean) removes the falsy entries and join() makes the space-separated class string.

JSFragment
// Ternary concat
class: 'tab' + (active ? ' active' : '')
class: 'col ' + (pct >= 0 ? 'positive' : 'negative')

// Array join - cleaner for multiple conditionals
class: ['btn', selected && 'selected', disabled && 'disabled'].filter(Boolean).join(' ')

Dynamic styles#

JSFragment
// Inline string
style: 'width:' + pct + '%;background:' + color

// On component root
this.style.height = height + 'px';

// css() helper - object to style string (not part of mx, just handy)
let css = o => Object.entries(o).map(([k, v]) => k + ':' + v).join(';');
style: css({ width: pct + '%', background: color, opacity: 0.8 })

Routing#

JSFragment
navigation.addEventListener('navigate', e => {
    let url = new URL(e.destination.url);
    if (url.origin !== location.origin) return;
    e.intercept({ handler: () => navigate(url.pathname) });
});

// SPA link
mx.a({ href: path, onclick: e => {
    e.preventDefault();
    navigation.navigate(path);
}}, label)

render() vs append()#

JSFragment
// render() - declarative: reconciles, reuses, handles conditionals, removes excess
container.render(
    mx.h1('Title'),
    showSub && mx.p('Subtitle'),  // false → skipped
    mx.div('Content')
);

// append() - imperative DOM: just adds nodes, no reconciliation
container.append(element);

Prefer render() everywhere, even where append() would work. It gives you declarative control, conditionals and cleanup for free.

Conventions#

RuleDoDon't
Variablesletconst / var
Defaultssize = 20size || 20
EventsonclickonClick
Numbersmx.span(count)mx.span(String(count))
Clearingel.textContent = ''el.innerHTML = ''
Callbacksonchange?.(v)onchange && onchange(v)
CSS unitspxrem

Common mistakes#

Sorting a prop in place
Array sort() mutates the parent's array. Copy first.
assets.sort(compareFn);
let sorted = [...assets].sort(compareFn);
Listeners in $()
addEventListener stacks another listener every render. Assign the property instead.
$() { this.addEventListener('click', () => doStuff()); }
$() { this.onclick = () => doStuff(); }
React event names
Event props are lowercase DOM properties.
mx.button({ onClick: fn })
mx.button({ onclick: fn })