Guide

Best practices

These small habits keep mx code fast, predictable and easy to change.

The three that matter most#

Most mx bugs trace back to one of these. Each is covered in detail below, next to the smaller rules.

Tip
Keep state in one place

One object per view, read by one render function. No state hiding in DOM nodes.

Tip
Re-render the container

Change the state, call render() again. mx updates only what differs.

Tip
Key stateful lists

Build rows with dom() and keep them in a Map, so a reorder moves nodes instead of rewriting them.

Lowercase event names#

Always use lowercase event names: onclick, oninput, onchange. This is the DOM standard. mx assigns on* functions straight to the element property, so onClick lands on a property the browser never calls. There's no error, and the handler just never fires.

Why doesn't onClick fire?

onClick, onChange, onInput are React conventions. In mx and the DOM they are onclick, onchange, oninput.
// never fires
button({ onClick: save }, 'Save')
// fires on click
button({ onclick: save }, 'Save')

Properties for live values#

For form elements, prefix the key with a . to set the live DOM property: '.value', '.checked', '.selectedIndex'. The HTML value attribute only sets the initial default, while the property controls what the user sees.

JS
// Set the live value property
input({ '.value': currentText })

// Set the checked property
input({ type: 'checkbox', '.checked': isChecked })

Inside render(), mx syncs the plain value, checked and selected keys to their properties as a convenience. $attrs() and dom() do not: there a plain key is setAttribute and nothing more, which stops moving the field once the user has typed in it.

My input value doesn't change

The attribute is the default the field started with. After an edit, only the property changes what is displayed.
// attribute only: the typed text stays
field.$attrs({ value: '' });
// property: the field clears
field.$attrs({ '.value': '' });

The . prefix works on every path and says what you mean, so prefer it for anything the user can edit.

Security#

mx renders string children as text nodes, which never parse markup, so they are safe from XSS. Attributes are not inert, so never put a user string on an on* key, where it becomes an inline handler that runs, and check the scheme of a user URL before it goes into href or src. Avoid innerHTML with user-supplied content. If you need to render HTML, provide a dedicated escape hatch and sanitize first.

User content through innerHTML

A string child is a text node. A string assigned to innerHTML is parsed as markup, scripts and handlers included.
// parses whatever the user wrote
div({ '.innerHTML': comment.body })
// a text node: markup shows as text
div(comment.body)

One source of truth#

Keep state in a single object, either a component's $state or a local variable, and re-render from it. Avoid scattering state across multiple variables or DOM nodes.

JS
// Good: state in one place
let state = { name: '', email: '', agreed: false };

function view() {
    let { form, label, input, button } = mx;
    return form({ onsubmit(e) { e.preventDefault(); alert(JSON.stringify(state)) } },
        label('Name'), input({ '.value': state.name, oninput(e) { state.name = e.target.value } }),
        label('Email'), input({ '.value': state.email, oninput(e) { state.email = e.target.value } }),
        button({ type: 'submit' }, 'Save')
    );
}

Re-render the container#

When state changes, re-render the whole container rather than surgically mutating individual nodes. This is usually simpler, and mx handles the efficient DOM updates under the hood.

JS
let state = { count: 0 };

function view() {
    return mx.div(
        mx.span(state.count),
        mx.button({ onclick() { state.count++; host.render(view()) } }, '+')
    );
}

let host = dom.div();
document.body.append(host);
host.render(view());

Hoist static data out of render#

A component's $ function re-runs every time the component renders, whether from this.$({...}) or a parent re-render. Anything defined inside it - option arrays, label maps, column definitions - is re-allocated on every render. Hoist constants to module or IIFE scope so they are built once.

Constants rebuilt on every render

The options never change, but a new array is allocated each time $ runs.
define('status-select', {
    $({ value }) {
        // a new array each render
        let options = ['active', 'paused', 'archived'];
        return mx.select({ '.value': value },
            ...options.map(o => mx.option(o))
        );
    }
});
// built once, reused by every render
let STATUS_OPTIONS = ['active', 'paused', 'archived'];

define('status-select', {
    $({ value }) {
        return mx.select({ '.value': value },
            ...STATUS_OPTIONS.map(o => mx.option(o))
        );
    }
});

This applies to anything static, such as column definitions for a table, label lookups, or formatter and icon maps. If it doesn't depend on props or state, it doesn't belong inside $.

Destructure from mx#

Pull the tags you need from mx at the top of your function. This keeps code tidy and saves a few characters per call.

JS
let { div, span, button, input, ul, li } = mx;

// Now use them directly
div({ class: 'app' },
    ul(
        li('Item 1'),
        li('Item 2')
    )
);

Guard component definitions#

When defining components in demos or lazy-loaded code, guard against double registration. The components global is a plain object, so check it before calling define():

JS
if (!components['my-widget']) {
    define('my-widget', {
        $({ label }) {
            return mx.div({ class: 'widget' }, label);
        }
    });
}

// Safe to call multiple times
document.body.render(mx.myWidget({ label: 'Hello' }));

Use dom() for persistent references#

When you need to call .$() on a component later (from an event handler or a timer, say), create it with dom() instead of mx(). dom() returns the real element immediately. mx() returns a description, which is an array, not an element.

// mx() returns a description, not an element
let picker = mx.datePicker({ selectedDate: new Date() });

// TypeError: picker is an array
picker.$({ selectedDate: new Date() });
// dom() creates the real element - call .$() on it later
let picker = dom('date-picker', { selectedDate: new Date() });

// Update from an external event
button.onclick = () => {
    picker.$({ selectedDate: new Date() });
};

Do I need keys for lists?#

Not by default. mx updates positionally: it walks children left to right and reuses nodes by tag name. This is fine for most lists. But if rows contain stateful elements (toggles, checkboxes) and you reorder, the state stays in place while the data moves around it.

The fix is simple: create real DOM elements with dom() and store references. render() identity-matches real DOM nodes - it moves them physically instead of diffing, so the element's properties and component state travel with it:

JS
// Create a persistent DOM element per data item
let rowMap = new Map(
    data.map(d => [d.id, dom('a-row', { columns, data: d })])
);

// Render into table
table.render(...data.map(d => rowMap.get(d.id)));

// On sort: reorder references - render moves the actual nodes
let sorted = [...data].sort((a, b) => a.name.localeCompare(b.name));
table.render(...sorted.map(d => rowMap.get(d.id)));

// Update a single row's data without recreating it
rowMap.get(id).$({ columns, data: newData });

This works because render() compares real nodes by identity (===). Same node in the same slot is a no-op, and a different node gets moved. It relies on DOM identity rather than any framework bookkeeping.

Prune keys that leave the data

A Map keyed by id keeps growing as long as you only add to it. When items disappear from the data, their entries linger. That's a slow leak, and a stale row can resurface if an id is later reused. Diff the incoming ids against the map's keys and delete the ones that are gone:

JS
let live = new Set(data.map(d => d.id));
for (let id of rowMap.keys())
    if (!live.has(id)) rowMap.delete(id);   // drop rows no longer present

let rows = data.map(d =>
    rowMap.get(d.id) ?? rowMap.set(d.id, dom('a-row', { columns, data: d })).get(d.id)
);
table.render(...rows);

The edge cases of mixing positional and identity rendering are on the Gotchas page.

How do components talk to each other?#

Three ways, from simplest to most flexible:

CallbacksPass functions as props: mx('my-comp', { onchange: fn }). The component calls it when something happens. Best for parent-child communication.
Shared stateComponents read from and write to a shared object, then re-render their container. Best for siblings in the same view.
Event busA tiny pub/sub for decoupled communication across the app, below.
JS
// Simple event bus (10 lines)
let bus = (() => {
    let subs = new Map;
    return {
        on(e, fn) {
            if (!subs.has(e)) subs.set(e, new Set);
            subs.get(e).add(fn);
        },
        send(e, data) { subs.get(e)?.forEach(fn => fn(data)); }
    };
})();

// Component A sends
bus.send('user-selected', { id: 42 });

// Component B listens
bus.on('user-selected', user => {
    detailPanel.$({ userId: user.id });
});

Is this like React?#

It works with plain DOM and a tiny helper, without a virtual DOM or required JSX. mx creates lightweight descriptions that render() reconciles against live DOM nodes. There are no lifecycle hooks, hooks or built-in state management on top of the DOM.

If you want JSX, use any transform that outputs calls to mx, but it's not required.

Key differences from React

  • No virtual DOM: mx patches real DOM directly.
  • No JSX required: use plain JS function calls.
  • No build step: drop a script tag and go.
  • this in event handlers refers to the actual DOM element.
  • Event names are lowercase (onclick, not onClick).
  • Under 1 KB brotli, while React + ReactDOM is about 60 times the size.

Checklist#

Before you ship

  • Lowercase events: onclick, not onClick.
  • Properties for live values: '.value', '.checked', '.selectedIndex'.
  • Security: prefer text children (mx makes them text nodes) over innerHTML, and keep user strings out of on* keys and unchecked URLs.
  • One source of truth: keep state in a single object and re-render from it.
  • Re-render containers: it's usually simpler, and mx updates efficiently.
  • Hoist static data: option arrays, column defs and label maps go to module scope, not inside $.
  • Destructure from mx to keep code tidy.
  • Guard definitions: check components[name] before define().
  • dom() for references: use dom() when you need to call .$() later.
  • Key stateful lists: dom() nodes in a Map, pruned when ids leave the data.