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()mx.tag(attrs?, ...children)Shorthand via Proxydom(tag, attrs?, ...children)Create a real DOM elementdom.tag(attrs?, ...children)Shorthand via Proxydefine(name, { $, ... })Register a componentcomponentsComponent registryel.render(...nodes)Reconcile children into the elementel.$attrs(attrs)Batch-set attributes and propertiesel.$(props?)Update component state and re-renderel.$statePersistent state across rendersAttributes#
| Syntax | Behavior | Example |
|---|---|---|
| name: 'value' | setAttribute | class: 'active' |
| '.name': value | el[name] = value | '.value': text |
| name: null | removeAttribute | disabled: null |
| name: false | removeAttribute | hidden: false |
| name: true | setAttribute(name, 'true') | disabled: true |
| key: fn | el[key] = fn (any function) | onclick: handler |
| value / checked / selected | In render(): attribute + property | value: text |
render() rules#
| Input | Behavior |
|---|---|
mx.tag(...) | Create or reuse by tag name, update attrs, recurse into children |
| Real DOM node | Identity match by reference: same node is a no-op, a different one moves |
| String / Number | Create or update a text node (numbers auto-cast) |
| Plain array | Flattened into the child list, nested arrays too (mx 1.4.1 and earlier: spread it) |
null / undefined / false | Skipped: 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.
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#
// 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#
// 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() unsubscribesConditional rendering#
Use JavaScript's logical AND or conditional operator to choose a child.
// 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.
// 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#
// 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#
// 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#
$({ 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.
// 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#
// 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#
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()#
// 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#
| Rule | Do | Don't |
|---|---|---|
| Variables | let | const / var |
| Defaults | size = 20 | size || 20 |
| Events | onclick | onClick |
| Numbers | mx.span(count) | mx.span(String(count)) |
| Clearing | el.textContent = '' | el.innerHTML = '' |
| Callbacks | onchange?.(v) | onchange && onchange(v) |
| CSS units | px | rem |
Common mistakes#
sort() mutates the parent's array. Copy first.assets.sort(compareFn);let sorted = [...assets].sort(compareFn);addEventListener stacks another listener every render. Assign the property instead.$() { this.addEventListener('click', () => doStuff()); }$() { this.onclick = () => doStuff(); }mx.button({ onClick: fn })mx.button({ onclick: fn })