Core
Components with define()
A component is an ordinary DOM element plus the methods you register for its tag. Its $ turns props into children, and you call .$() to update it. There is no custom-element registry, Shadow DOM or lifecycle to learn.
define(tagName, { $(props) { ... } })Registers an object of methods for a tag. Every HTML element of that tag created by mx or dom gets them (SVG elements do not). Inside the methods, you have:
| Member | What it is |
|---|---|
| this | The actual DOM element |
| this.$attrs(attrs) | Efficiently set multiple attributes |
| this.$state | Component state object: props accumulate here |
| this.render(...children) | Update children |
- Createmx.
my Card(props) or dom() - Render$(props) returns the children
- Update.$({ ... }) merges and re-renders
Key ideas
- Use
define()for reusable components and plain functions for one-off view fragments. - A component is a boundary: props are the only way in. Positional children are dropped.
$stateholds props (the public surface), whilethis._xholds private bookkeeping.- Methods beyond
$become an imperative API on every instance, even on built-in tags.
define() components#
For reusable components, use define(tagName, { $() {...} }) to register mx component methods on ordinary DOM elements. The $ function receives props and returns children to render. Here's a simple row component:
define('a-row', {
$({ columns, data }) {
let { div } = mx;
return columns.map(col => {
let value = col.fn?.(data[col.key], data) ?? data[col.key];
return div({ class: 'table-cell' }, value);
});
}
});
// Use it
let columns = [
{ key: 'name', label: 'Name' },
{ key: 'age', label: 'Age' }
];
let user = { name: 'Alice', age: 25 };
document.body.render(
mx.aRow({ columns, data: user })
);Components can compose other components:
define('a-row', {
$({ columns, data }) {
let { div } = mx;
return columns.map(col => {
let value = col.fn?.(data[col.key], data) ?? data[col.key];
return div({ class: 'table-cell' }, value);
});
}
});
define('a-table', {
$({ columns = [], data = [] }) {
let { div } = mx;
let header = div({ class: 'table-header' },
...columns.map(col => div({ class: 'table-cell' }, col.label || col.key))
);
let rows = data.map((item, index) =>
mx.aRow({ columns, data: item, index })
);
return [header, ...rows];
}
});
// Use it
document.body.render(
mx.aTable({
columns: [{ key: 'name' }, { key: 'age' }],
data: [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]
})
);Use define() for reusable state and methods. It does not register browser custom elements or create Shadow DOM encapsulation.
Functions (local fragments)#
Functions are useful for local, view-specific fragments that you don't need to reuse. For most reusable components, prefer define().
let { div, span } = mx;
// Local helper for this view only
let statusBadge = status => {
let color = status === 'active' ? 'green' : 'gray';
return span({ class: 'badge', style: `color: ${color}` }, status);
};
// Use inline in your view
document.body.render(
div({ class: 'user-card' },
div('Username'),
statusBadge('active')
)
);| Reach for | When |
|---|---|
| a function | Local helpers, view-specific fragments, one-off compositions |
| define() | Reusable components, components needing state or methods, shared UI elements |
Components are boundaries#
define() creates a hard boundary. Inside it, the component owns its DOM, its state, and what it renders. Outside it, you talk to the component through one channel: props.
// mx.p('body text') is dropped -
// $ receives only { title: 'Hello' }
mx.myCard({ title: 'Hello' },
mx.p('body text'))mx.myCard({
header: mx.h2('Title'),
body: mx.p('Body text'),
footer: mx.button('OK')
})This is by design. The reconciler knows two kinds of children: things to mount into a plain element's tree, and props to hand to a component's $. Positional children fit the first model and not the second.
Imagine a card that wants header, body and footer slots. With positional children you'd need:
mx.myCard({...}, header, body, footer)
mx.myCard({...}, , body, footer) // illegal - JS has no empty call arguments
mx.myCard({...}, undefined, body, footer) // works, but uglier than propsPosition 0 is "header". How do you skip it cleanly? You can't, without a sentinel value or a wrapper object. And once you're passing a wrapper object, you're back to props, just spelled awkwardly. Named slots are where positional children end up anyway.
There's a render-side problem too: positional children would have to be reconciled differently per component (this card's position 0 is a header, that menu's position 0 is a trigger). Props let each component define its own slot semantics without baking a special syntax into the framework.
The fix is to pass slots as named props. They can hold anything you'd normally render (mx descriptions, DOM nodes, arrays, strings), and the component decides where each one goes:
define('my-card', {
$({ header, body, footer }) {
return mx.div({ class: 'card' },
mx.div({ class: 'card__header' }, header),
mx.div({ class: 'card__body' }, body),
mx.div({ class: 'card__footer' }, footer)
);
}
});
mx.myCard({
header: mx.h2('Title'),
body: mx.p('Body text'),
footer: mx.button('OK')
})The named slots section below shows a plain-function component that does receive positional children, because it's just a function call and the args go where you put them. Functions aren't boundaries and compose by call, while define() components are boundaries and compose by props. Pick the tier that matches what you need.
Named slots#
Pass children by name using a plain object, without needing Shadow DOM. The same idea works two ways: as a function (compose at the call site), or inside a define() component (compose at the boundary, as above).
let { div, h3, p, button } = mx;
let card = (props = {}, kids = []) => {
let slots = Array.isArray(kids) ? { default: kids } : kids;
return div({ class: 'card' },
div({ class: 'card__header' }, ...(slots.header || [])),
div({ class: 'card__body' }, ...(slots.default || [])),
div({ class: 'card__footer' }, ...(slots.footer || []))
);
};
document.body.render(
card({}, {
header: [h3('Title')],
default: [p('Body text')],
footer: [button('OK')]
})
);Icon component (SVG rendering)#
Components aren't limited to HTML elements. An icon component that renders SVG paths from a dictionary is a scalable, flexible way to manage icons across your app:
let icons = {
check: 'M5 12l5 5L20 7',
close: 'M6 6l12 12M18 6L6 18',
star: 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01z',
upload: 'M12 15V3m0 0L7 8m5-5l5 5M4 17v2a2 2 0 002 2h12a2 2 0 002-2v-2'
};
define('an-icon', {
$({ icon, color }) {
this.style.color = color || '';
return mx.svg({ viewBox: '0 0 24 24', width: 24, height: 24, fill: 'none', stroke: 'currentColor', 'stroke-width': 2 },
mx.path({ d: icons[icon] || '' })
);
}
});
// Use it
document.body.render(
mx.div({ style: 'display:flex; gap:16px' },
mx.anIcon({ icon: 'check' }),
mx.anIcon({ icon: 'star', color: 'gold' }),
mx.anIcon({ icon: 'upload', color: '#4285f4' }),
mx.anIcon({ icon: 'close', color: '#ea4335' })
)
);Inside an mx.svg() host, children such as mx.path() and mx.circle() are created in the SVG namespace. Attributes like viewBox and stroke-width are set via setAttribute, as expected. A top-level mx.path() outside an svg host and camelCase tags such as mx.clipPath() render nothing, as the SVG gotchas explain.
define('chart-bar', { $({ x }) { return mx.rect({ x, width: 10, height: 50 }); } });
// ✗ component as a direct SVG child -> $ never runs, renders nothing
root.render(mx.svg({ viewBox: '0 0 100 100' }, mx.chartBar({ x: 0 })));// ✓ invert it: the component's $ RETURNS the svg
define('bar-chart', { $({ data }) {
return mx.svg({ viewBox: '0 0 100 100' },
...data.map((v, i) => mx.rect({ x: i * 12, width: 10, height: v })));
} });
root.render(mx.barChart({ data: [40, 50, 30] }));Rule of thumb: a component owns an SVG subtree by returning mx.svg(...) from its $. It is never itself a raw SVG child.
Stateful components ($state)#
Components hold persistent state in this.$state, which accumulates across $() calls via Object.assign. Destructure props with defaults at the top of $, and call this.$({...}) to update. You rarely touch $state directly.
define('a-counter', {
$({ count = 0, step = 1 }) {
let { div, button, span } = mx;
return div(
button({ onclick: _ => this.$({ count: count - step }) }, '−'),
span(count),
button({ onclick: _ => this.$({ count: count + step }) }, '+')
);
}
});
document.body.render(
mx.aCounter({ count: 10, step: 5 })
);Updating components externally#
Use dom() to get a real element reference, then call el.$({ ... }) to push new props into the component at any time:
define('step-indicator', {
$({ steps = [], currentStep = 1 }) {
let { div } = mx;
return steps.map((step, i) => {
let n = i + 1;
let state = n < currentStep ? 'done' : '';
if (n === currentStep) state = 'active';
return div({ class: 'step ' + state },
div({ class: 'circle' }, n < currentStep ? '✓' : n),
div({ class: 'label' }, step)
);
});
}
});
// Create with dom() - get a real element
let stepper = dom('step-indicator', {
steps: ['Account', 'Profile', 'Confirm'],
currentStep: 1
});
// Later, advance the step
stepper.$({ currentStep: 2 });
// Even later
stepper.$({ currentStep: 3 });| Call | Returns | Use it |
|---|---|---|
| mx() | A description (an array with ._ = 1) | Inside render() calls, where mx manages the DOM |
| dom() | A real HTMLElement | When you need a persistent reference to call .$() on later |
Component naming rules#
The tag name you use at the call site and the name you pass to define() go through the same camelCase → kebab-case conversion, so they always resolve to the same string:
| Site | Conversion | Example |
|---|---|---|
| define(name, ...) | camelCase → kebab-case | 'myButton' → 'my-button' |
| mx.camelCase() | camelCase → kebab-case | mx.myButton() → 'my-button' |
| mx('string') | camelCase → kebab-case | mx('my-button') → 'my-button' |
So camelCase and kebab-case both work in define(). Kebab-case is the convention, since that is the tag the element actually gets:
// ✓ Both register 'my-button'
define('my-button', { $() {...} });
define('myButton', { $() {...} });
mx.myButton() // → <my-button>
mx('my-button') // → <my-button>
// ✗ Wrong - PascalCase produces a leading hyphen
define('MyButton', { $() {...} }); // stored as '-my-button'
mx.MyButton() // tag '-my-button': render() throws InvalidCharacterError (Chromium)A leading capital converts to a leading hyphen, which is not a valid element name. define() and mx.MyButton() do not complain. The failure comes at render, when createElement('-my-button') throws InvalidCharacterError in Chromium. Stick to camelCase or kebab-case.
What $ can return#
$ must return one of two shapes. Anything else either crashes or produces wrong output:
| Return value | Behavior |
|---|---|
mx.tag(...) (a single description) | render(value): rendered as the sole child |
[child, child, ...] (an array) | render(...value): spread as multiple children |
[] | No children: the element is emptied |
undefined / null / false / 0 / '' | Renders nothing: the wrapper guards with value?._ and ... || [] |
A string, e.g. 'hello' | Mis-renders: a string is iterable, so it spreads into one text node per character (textContent still reads right) |
Any other number, or true | Throws: spread on a non-iterable |
The wrapper dispatches via value?._ ? render(value) : render(...value || []). Only mx descriptions (arrays tagged with ._) and plain iterables work. null, undefined, false, 0 and '' fall through the || [] and render nothing, with no crash.
// ✓ Single description
define('greeting', {
$({ name }) {
return mx.div('Hello, ' + name);
}
});
// ✓ Array of children
define('counter', {
$({ count }) {
return [
mx.button('-'),
mx.span(count),
mx.button('+')
];
}
});
// ✓ Empty array to render nothing
define('conditional', {
$({ visible }) {
if (!visible) return [];
return mx.div('visible content');
}
});
// ✗ Forgot the return keyword - no crash, renders nothing:
// undefined falls through the || [] and the element is emptied
define('broken', {
$({ msg }) {
mx.div(msg); // not returned!
}
});Methods beyond $#
define(name, obj) does Object.assign(element, obj) on every matching HTML element created by mx or dom. So every property on the definition object becomes a property on the element, not just $:
define('video-player', {
$({ src, playing }) {
this._video ||= dom.video();
if (this._video.getAttribute('src') !== src) this._video.$attrs({ src });
if (playing) this._video.play();
else this._video.pause();
return [this._video];
},
// Imperative API methods - available on every instance
playPause() {
let v = this._video;
v.paused ? v.play() : v.pause();
},
seek(seconds) {
if (this._video) this._video.currentTime = seconds;
},
reset() {
this.$state = {};
this._video = null;
}
});
// Later, from anywhere:
let player = document.querySelector('video-player');
player.playPause();
player.seek(30);Useful for exposing an imperative API alongside the declarative $ flow. Think of it as what you'd put on a class prototype in a traditional component framework, except it's just Object.assign, so the properties are instance-own, not inherited.
define(name, {}) with no $ still registers the object as a methods mixin. Any element created with that tag gets the methods, but it is not a component: its props are set as attributes and its positional children render, as they would for a plain tag. That's occasionally useful but confusing if accidental.
Built-in tag methods and dom() attribute hooks#
define() doesn't check whether the tag name is custom or built-in. Both work the same way. Defining on a built-in tag means every instance of that tag created via mx or dom picks up your methods, including $ or a custom $attrs. This is a feature.
It works because createElement is the single entry point: every HTML element passes through Object.assign(element, components[tag]) on creation (SVG elements take the createElementNS branch and skip it). Whatever you put in the registry attaches to every fresh node of that tag, with no per-call-site change.
Pattern 1: hardening the platform
For explicit privacy and opener isolation, anchors with target="_blank" can set rel="noopener noreferrer" under this policy (read about reverse tabnabbing). Modern target=_blank links implicitly get noopener, and noreferrer additionally suppresses referrers. Define on a for dom() construction:
define('a', {
$attrs(attrs) {
if (attrs.target === '_blank' && !attrs.rel)
attrs = { ...attrs, rel: 'noopener noreferrer' };
return Element.prototype.$attrs.call(this, attrs);
}
});
// dom() invokes $attrs; mx() reconciliation does not.
dom.a({ href: 'https://example.com', target: '_blank' }, 'Link')
// → <a href="..." target="_blank" rel="noopener noreferrer">Link</a>Pattern 2: build-time expansion
If your build pipeline emits responsive image variants (foo.png, foo@2x.png, foo@3x.png), define on img to auto-build the srcset. Authors write one URL and the DOM gets all variants:
define('img', {
$attrs(attrs) {
if (attrs.src && /\.png$/.test(attrs.src) && !attrs.srcset) {
let base = attrs.src.replace(/\.png$/, '');
attrs = { ...attrs,
srcset: `${base}.png 1x, ${base}@2x.png 2x, ${base}@3x.png 3x`
};
}
return Element.prototype.$attrs.call(this, attrs);
}
});
dom.img({ src: '/hero.png', alt: 'Hero' })
// → <img src="/hero.png" alt="Hero" srcset="/hero.png 1x, /hero@2x.png 2x, /hero@3x.png 3x">Pattern 3: dom() construction defaults
Want every <video> to start muted and inline? Every <form> to preventDefault on submit? Every <dialog> to trap focus? Define it once. The hook runs only when dom() gets a props object, so dom.video() with no props and every mx.video() skip it (pass {} to get the defaults):
define('video', {
$attrs(attrs) {
// .muted: the muted attribute is only read at parse time, so set the property
attrs = { '.muted': true, playsinline: true, preload: 'metadata', ...attrs };
return Element.prototype.$attrs.call(this, attrs);
}
});
define('form', {
$attrs(attrs) {
let { onsubmit, ...rest } = attrs;
return Element.prototype.$attrs.call(this, { ...rest,
onsubmit: e => { e.preventDefault(); onsubmit?.(e); }
});
}
});
// This dom() attribute hook preserves the caller-provided children.
let form = dom.form({ onsubmit: () => console.log('Submitted') },
dom.input({ name: 'name' }), dom.button({ type: 'submit' }, 'Save'));
document.body.append(form);This is the same idea as a Lisp macro or a JSX pragma: the source you write differs from the DOM that's emitted, but the transformation is local and predictable. The definition is global, the effect is per element, and the cost is whatever your method does at element-creation time. The author of the call site doesn't need to know about it and just writes dom.a(...) to use this attribute hook. The reconciler applies mx() description attributes directly and does not call $attrs. Use an explicit helper to supply description defaults.
Method mixins on built-in tags affect every call site that uses mx.a, mx.img and so on, including code you don't own (third-party widgets, future contributors, your future self after a year). If you define('div', ...) to add a logging side effect, you've made every <div> in the app expensive.
Reserve this pattern for behavior that should be true of every instance with no exceptions, such as security defaults, build-time conventions or project-wide accessibility rules. If only some instances need it, use a custom tag (mx.safeAnchor(...)) instead.
$state vs this._property#
Teams adopting mx ask this more than anything else. The two are separate tiers with different rules, and you rarely want to mix them.
| this.$state.x | this._x | |
|---|---|---|
| What it holds | Accumulated props from the parent | Internal bookkeeping: tracking values, DOM refs, caches, flags, timers |
| Who writes it | The parent (via el.$({...})) and the component itself (via this.$({...})) | Only the component itself |
| Merge behavior | Object.assign(this.$state, props) runs before every $() call | Plain own property: set directly, no merge |
| Read from outside | OK, for aggregation (e.g. form submit reading nameField.$state.value) | Forbidden: it's private |
| Write from outside | Forbidden: always go through comp.$({ key: newValue }) so the change flows through the declarative model | Forbidden: it's private |
Rule: pick the narrowest tier that holds the data's actual lifetime. If a parent needs to see or set it, it's $state. Everything else is this._.
define('player', {
$({ track, playing, progress = 0, onEnded }) {
// $state: props surface. The parent controls track + playing + progress.
// Sibling components can read them: player.$state.track, .progress, etc.
// _interval: internal bookkeeping. The parent has no business seeing it.
clearInterval(this._interval);
if (playing) {
this._interval = setInterval(() => {
let next = progress + 1;
if (next >= track.duration) onEnded?.();
this.$({ progress: next });
}, 1000);
}
// _waveCache: memoized per-track computation. Purely private.
if (track && this._waveTrack !== track.id) {
this._waveTrack = track.id;
this._waveBars = computeBars(track);
}
return [mx.div(track.title), mx.progress({ value: progress, max: track.duration })];
}
});Putting _interval, Maps, DOM refs or any private data into $state pollutes the props namespace and risks collisions with props the parent might pass. It also makes the component look like it accepts those keys as props, which leaks implementation details to callers. Keep $state as the external API surface and this._ as internal memory.
Form submit handlers often aggregate $state from several sub-components:
// ✓ Reading is fine - standard pattern for form submit
function submit() {
return api.post('/users', {
name: nameField.$state.value,
role: roleDropdown.$state.selected,
avatar: fileInput.$state.files?.[0]
});
}
// ✗ Writing from outside is forbidden - bypasses the declarative flow
nameField.$state.value = 'Alice'; // don't do this
// ✓ Always go through $()
nameField.$({ value: 'Alice' });Calling this.$({}) with an empty object merges nothing into $state and then re-invokes $ with unchanged state. If you find yourself writing this, the component is relying on this._ mutations as side effects and using $({}) to flush a render. That hides what actually changed and defeats the declarative model.
Fix: pass the actual changed values: this.$({ progress: newValue }). If a child callback triggered the re-render, have the callback pass data back to the parent as props (onChange, onSelect) and let the parent re-render with meaningful state.