Guides

Patterns for real apps

You'll find tables, virtual scroll, drag and drop, pickers and forms here, each built from plain mx and running live. Open a Result tab, click around, then read the code. None of it is a library feature, so copy whatever fits.

.map()
Lists and conditionals

Map arrays to children, branch with ternaries, re-render the container.

See the demo
Composition
Cards with named slots

Pass children by name in a plain object. No Shadow DOM.

See the demo
$state
Sortable table

Sort key and direction live in $state, and a header click re-renders.

See the demo
Performance
Virtual scrolling

10,000 rows, and only the visible ones in the DOM.

See the demo
$state
Date picker

The viewed month and the picked day, tracked independently.

See the demo
Re-render
Todo app

Local variables, one view function, a full re-render per change.

See the demo
Events
Drag and drop

HTML5 drag events reorder a list, and Alt+arrows do it by keyboard.

See the demo
Events
File drop zone

Drag handlers on the component element plus a hidden file input.

See the demo
$attrs
Computed attributes

Derive values from props and expose them to CSS as attributes.

See the demo

Every component here has the same shape:

  1. define()one $ render function
  2. props + $statemerged, kept across renders
  3. return mx(...)descriptions, not nodes
  4. this.$()a handler merges and re-runs $

mx() or dom()?#

This is the one distinction worth getting right, because every other pattern here rests on it. Both build elements from the same tag-proxy syntax. The difference is what you get back, and therefore what you can do next:

  • mx.div(...) returns a description - a tiny array marked ._ = 1. It is not in the DOM and isn't an element. render() turns it into (or reconciles it against) real nodes.
  • dom.div(...) returns a real element, created and attribute-applied immediately. You can hold it, append it, query it and call methods on it.

Put simply, mx() describes an element and dom() creates one. If you're saying "here's what should be on screen," that's mx(), and it belongs inside a render() or a component's $. If you need the element as a value - to keep a reference, mutate it later, or hand it to code that isn't mx - that's dom().

The default: mx() inside render

Ninety percent of the elements you write are descriptions. Inside a component, a view or any render() call, reach for mx. You never hold these because the reconciler owns them.

JS
// Inside render() / a component's $: describe the tree with mx().
// These are throwaway descriptions - mx reconciles them against the DOM.
define('user-card', {
  $({ user }) {
    return mx.div({ class: 'card' },
      mx.img({ src: user.avatar }),
      mx.h3(user.name),
      mx.button({ onclick: () => follow(user.id) }, 'Follow')
    );
  }
});

Reach for dom() when you need the element later

The sign is a sentence with "later" or "then" in it: create it now, then remove it / update it / read it / pass it somewhere. A description can't do any of that - it's not an element yet.

JS
// dom() returns a REAL element you keep and talk to later.

// A toast you'll remove yourself:
let toast = dom.div({ class: 'toast' }, 'Saved');
document.body.append(toast);
setTimeout(() => toast.remove(), 3000);       // you hold the node, so you can remove it

// A component you'll push updates into:
let chart = dom('chart-card', { data: series });
panel.append(chart);
chart.$({ data: nextSeries });                // call .$() on the live element later

// A field you read on submit (no re-render needed - the DOM owns the value):
let nameField = dom.input({ name: 'name' });
form.append(nameField);
onSubmit(() => save(nameField.value));

Keyed lists: dom() refs you move, not rebuild

This is the sharpest case. When list items carry state you must preserve across reorders (an open menu, a typed value, component state), keep a persistent dom() element per key in a Map, update each in place, and return the real nodes. render() matches real nodes by identity and physically moves them rather than recreating them. It moves as few nodes as it can, and the ones left in place keep focus and scroll position. A node that does move loses focus and scroll position and restarts CSS animations, as with any DOM move:

JS
define('board', {
  $({ cards = [] }) {
    // Keep one persistent element per id. Reordering then MOVES the same
    // nodes, keeping their properties and component state, instead of
    // rebuilding them. A node that moves loses focus and scroll position
    // and restarts CSS animations, like any DOM move. Nodes left in place keep them.
    let map = this._cards ??= new Map;
    for (let [id] of map)
      if (!cards.find(c => c.id === id)) map.delete(id);          // drop removed

    cards.forEach(c => {
      let el = map.get(c.id);
      if (!el) map.set(c.id, el = dom('board-card'));   // create once, keep the ref
      el.$({ card: c });                                // one update path - new or existing
    });

    // Returning real nodes: render() matches them by identity and moves them
    return cards.map(c => map.get(c.id));
  }
});

The decision table

ScenarioUseWhy
Markup inside a component's $mx()Throwaway description the reconciler owns
Children passed to render()mx()Same - descriptions are what render consumes
A handle you'll call .$() on laterdom()You need the live element to update it
A node you'll append/remove yourselfdom()Toasts, portals, manual mounting
Per-item element in a keyed listdom()Move by identity to keep element and component state instead of rebuilding
A persistent child kept across re-rendersdom() on this._Survives the parent's $ re-running
Something handed to a non-mx librarydom()Charts, editors, maps need a real node
The app's mount pointexisting elementdocument.getElementById('app').render(...)
The most common mistake

Reaching for mx() and then trying to grab the element back - mx.div(...) followed by document.querySelector to find what you just "made." If you need the element, you wanted dom() from the start, because mx() never created a node for you to find.

The flip side is rarer but real: building a whole static page with dom() when you'll never touch those elements again wastes the reconciler - mx() + one render() is leaner.

They compose

A dom() element's children are usually mx() descriptions: dom.div(mx.h3(title), mx.p(body)) (an mx description isn't a plain object, so it's taken as a child - no empty {} needed, with real attributes passed as the first arg only when you have them). You hold the outer node and the reconciler manages its contents.

And dom('my-component', {...}) on a registered component calls its $ and returns the live element, which connects the two. Full API details in the Reference.

Lists and conditionals#

Rendering a list is just .map(), and conditionals are ternaries or && (guard numbers with !!, see Gotchas). Re-render the container when data changes and mx updates it efficiently.

JSRunnablePlayground
let { ul, li, button, div } = mx;

let items = ["alpha", "beta"];

let host = dom.div();

function view(){
  return div(
    ul( ...items.map(x => li(x)) ),
    button({ onclick(){ items.push("item " + (items.length+1)); host.render(view()); } }, "Add"),
    button({ onclick(){ items.pop(); host.render(view()); } }, "Remove")
  );
}

host.render(view());
document.body.render(host);

Re-rendering a container is usually simpler than surgically mutating children. mx updates efficiently.

Cards with named slots#

Pass children by name using a plain object, without needing Shadow DOM. The Card function checks whether kids is an array or an object to support both default children and named slots.

JSRunnablePlayground
let { div, h4, p, button } = mx;

let Card = (props = {}, kids = []) => {
  let slots = Array.isArray(kids) ? { default: kids } : kids;
  return div({ class:"card" },
    div({ class:"card__header" }, h4(props.title || "Card") ),
    div({ class:"card__body" }, ...(slots.default || []) ),
    div({ class:"card__footer" }, ...(slots.footer || []) )
  );
};

document.body.render(
  Card({ title:"Welcome" }, {
    default: [ p("Cards compose apps nicely.") ],
    footer: [ button("Close") ]
  })
);

Sortable table#

A sortable table component. Sort state lives in $state, so clicking a column header toggles the sort direction and re-renders. The header labels are buttons, so the sort works from the keyboard too.

JSRunnablePlayground
define('sortable-table', {
  $({ data = [], columns = [] }) {
    let { table, thead, tbody, tr, th, td, button } = mx;
    let sortKey = (this.$state.sortKey ??= columns[0]?.key);
    let asc = (this.$state.asc ??= true);
    let dir = asc ? 'ascending' : 'descending';

    let sorted = [...data].sort((a, b) => {
      let val = asc ? 1 : -1;
      return a[sortKey] > b[sortKey] ? val : -val;
    });

    return table(
      thead(tr(...columns.map(col =>
        // aria-sort tells screen readers which column is sorted, and how
        th({ 'aria-sort': sortKey === col.key ? dir : null }, button({ onclick: () => this.$({
          sortKey: col.key,
          asc: sortKey === col.key ? !asc : true
        })},
          col.label || col.key,
          sortKey === col.key ? (asc ? ' ↑' : ' ↓') : ''
        ))
      ))),
      tbody(...sorted.map(u =>
        tr(...columns.map(col => td(u[col.key])))
      ))
    );
  }
});

let users = [
  { name: "Alice", age: 25, city: "NYC" },
  { name: "Bob", age: 30, city: "LA" },
  { name: "Charlie", age: 35, city: "Chicago" },
  { name: "Diana", age: 28, city: "Miami" },
  { name: "Ethan", age: 42, city: "Seattle" }
];

document.body.render(
  mx.sortableTable({
    columns: [
      { key: "name", label: "Name" },
      { key: "age", label: "Age" },
      { key: "city", label: "City" }
    ],
    data: users
  })
);

Virtual scrolling#

For large lists (thousands of items), render only visible rows. A virtual-container component keeps the DOM small by rendering only what's on screen:

JS
define('virtual-container', {
  $({ height = 400, rowHeight = 48, rows = [] }) {
    this._visibleRows = Math.ceil(height / rowHeight) + 1;
    this._lastOffset = 0;
    this.style.cssText = `display:block;height:${height}px;overflow-y:auto;overflow-x:hidden`;

    let renderVisible = offset => {
      let visible = rows.slice(offset, offset + this._visibleRows);
      return [
        mx.div({ style: `height:${offset * rowHeight}px` }),
        ...visible,
        mx.div({ style: `height:${(rows.length - offset - visible.length) * rowHeight}px` })
      ];
    };

    this.onscroll = e => {
      let scrollTop = Math.max(0, e.target.scrollTop);
      let offset = Math.floor(scrollTop / rowHeight);
      if (offset === this._lastOffset) return;
      this._lastOffset = offset;
      this.render(...renderVisible(offset));
      this.scrollTop = scrollTop;
    };

    return renderVisible(0);
  }
});

Use it with large datasets:

JS
// Generate 10,000 items
let largeDataset = Array.from({ length: 10000 }, (_, i) =>
  mx.div({
    class: 'row',
    style: 'box-sizing: border-box; height: 48px; padding: 12px; border-bottom: 1px solid #8884;'
  }, `Item ${i + 1}`)
);

document.body.render(
  mx.virtualContainer({
    height: 400,
    rowHeight: 48,
    rows: largeDataset
  })
);
How it works

Spacer divs above and below the visible slice keep the full scroll height, while only the rows in view are rendered (ten here: enough 48px rows to fill the 400px box even when it is scrolled mid-row) instead of all 10,000. The DOM stays small no matter how long the list gets.

Date picker#

A calendar component using $state to track the viewed month and the selected date independently, so navigating months preserves the selection. Days are buttons with aria-pressed, so the picked one is announced.

JSRunnablePlayground
define('mini-calendar', {
  $({ selected, onSelect }) {
    let { div, span, button, table, thead, tbody, tr, th, td } = mx;

    let picked = (this.$state.picked ??= selected || new Date);
    // Always the 1st: setMonth() on the 31st would overflow a short month
    let view = (this.$state.view ??=
      new Date(picked.getFullYear(), picked.getMonth(), 1));

    let year = view.getFullYear();
    let month = view.getMonth();
    let daysInMonth = new Date(year, month + 1, 0).getDate();
    let firstDay = view.getDay();

    let days = [];
    for (let i = 0; i < firstDay; i++) days.push("");
    for (let d = 1; d <= daysInMonth; d++) days.push(d);

    // Highlight only when viewing the picked date's month
    let pickedDay = picked.getFullYear() === year
      && picked.getMonth() === month ? picked.getDate() : 0;
    // Roving tabindex: one day is the grid's only Tab stop
    let focusDay = Math.min(this.$state.focus || pickedDay || 1, daysInMonth);
    let go = (date, focus = 0) => this.$({
      view: new Date(date.getFullYear(), date.getMonth(), 1), focus
    });

    return [
      div(
        button({ 'aria-label': 'Previous month',
          onclick: () => go(new Date(year, month - 1, 1)) }, "‹"),
        // aria-live announces the new month after Prev / Next
        span({ 'aria-live': 'polite' },
          `${view.toLocaleString('default', { month: 'long' })} ${year}`),
        button({ 'aria-label': 'Next month',
          onclick: () => go(new Date(year, month + 1, 1)) }, "›")
      ),
      table(
        thead(tr(...["Su","Mo","Tu","We","Th","Fr","Sa"]
          .map(d => th(d)))),
        tbody(...Array.from(
          { length: Math.ceil(days.length / 7) }, (_, w) =>
          tr(...days.slice(w * 7, (w + 1) * 7).map(day =>
            td(day && button({
              'aria-pressed': String(day === pickedDay),
              tabindex: day === focusDay ? '0' : '-1',
              onclick: () => {
                this.$({ picked: new Date(year, month, day), focus: day });
                onSelect?.(new Date(year, month, day));
              },
              // Arrows move by day and week, across month edges too
              onkeydown: e => {
                let step = { ArrowLeft: -1, ArrowRight: 1,
                  ArrowUp: -7, ArrowDown: 7 }[e.key];
                if (!step) return;
                e.preventDefault();
                let to = new Date(year, month, day + step);
                go(to, to.getDate());
                this.querySelector('td [tabindex="0"]').focus();
              }
            }, day))
          ))
        ))
      )
    ];
  }
});

document.body.render(mx.miniCalendar());

Todo app#

A classic Todo app in mx. State lives in local variables and the entire view re-renders on every change. mx handles minimal DOM updates under the hood.

JSRunnablePlayground
let { div, h3, input, button, ul, li, label } = mx;

let todos = [];
let text = "";

function TodoApp(){
  return div({ class:"todo" },
    h3("Todos"),
    div(
      input({ "aria-label": "New todo", ".value": text, oninput: e => {
        text = e.target.value;
        todoHost.render(TodoApp());
      }}),
      button({ onclick: () => {
        if (text.trim()) {
          todos.push({ text, done: false });
          text = "";
          todoHost.render(TodoApp());
        }
      } }, "Add")
    ),
    ul( ...todos.map((t, i) =>
      li({ class: t.done ? "done" : "" },
        label(
          input({ type:"checkbox", ".checked": t.done, onchange: () => {
            t.done = !t.done;
            todoHost.render(TodoApp());
          }}),
          t.text
        ),
        button({ "aria-label": "Delete " + t.text, onclick: () => {
          todos.splice(i, 1);
          todoHost.render(TodoApp());
        } }, "×")
      )
    ))
  );
}

let todoHost = dom.div();
todoHost.render(TodoApp());
document.body.render(todoHost);

Drag and drop reordering#

HTML5 drag events work naturally with mx. A reorderable list component tracks the dragged index in $state and splices on drop. Each item is focusable, and Alt+Up / Alt+Down moves it without a mouse.

JSRunnablePlayground
define('drag-list', {
  $({ items = [], hint, onReorder }) {
    let { div, span } = mx;
    this.$attrs({ role: 'list' });
    let move = (from, to) => {
      let arr = [...items];
      let [moved] = arr.splice(from, 1);
      arr.splice(to, 0, moved);
      this.$({ items: arr, over: null });
      onReorder?.(arr, moved);
    };
    // The drop target's highlight is state too: re-render, don't poke styles
    let over = i => this.$state.over !== i && this.$({ over: i });

    return items.map((item, i) =>
      div({
        class: this.$state.over === i ? 'drag-item over' : 'drag-item',
        role: 'listitem',
        'aria-describedby': hint,
        draggable: 'true',
        tabindex: '0',
        ondragstart: () => { this.$state.dragging = i; },
        ondragover: e => { e.preventDefault(); over(i); },
        ondragend: () => over(null),
        ondrop: () => move(this.$state.dragging, i),
        // Keyboard: Alt+Up / Alt+Down moves the focused item
        onkeydown: e => {
          let to = i + ({ ArrowUp: -1, ArrowDown: 1 }[e.key] || 0);
          if (!e.altKey || to === i || !items[to]) return;
          e.preventDefault();
          move(i, to);
          this.children[to].focus();
        }
      },
        span({ class: 'handle', 'aria-hidden': 'true' }, '⋮⋮'),
        span(item)
      )
    );
  }
});

// The hint is read with each row; the status line announces every move
let status = dom.p({ role: 'status' });
document.body.render(
  mx.p({ id: 'drag-hint' }, 'Drag a row, or focus it and press Alt+Up / Alt+Down.'),
  mx.dragList({
    items: ['Learn mx', 'Build components', 'Ship to prod', 'Profit'],
    hint: 'drag-hint',
    onReorder: (arr, item) => status.textContent =
      `${item} moved to position ${arr.indexOf(item) + 1} of ${arr.length}`
  }),
  status
);

Use ondragstart to store the source index, ondragover with e.preventDefault() to allow dropping, and ondrop to splice the array and re-render. Route the keyboard path through the same move() so both stay in sync.

File drop zone#

A drop zone component combines drag events with a hidden file input. Events are assigned directly on this so re-renders overwrite the same property instead of stacking listeners. The visible target is a button, so it is reachable by Tab and opens the file picker with Enter.

JSRunnablePlayground
define('drop-zone', {
  $({ ondrop, accept }) {
    let { button, input, span } = mx;
    let handleFiles = files => ondrop?.(Array.from(files));

    // Direct assignment - safe on re-render (overwrites, never stacks)
    this.ondragover = e => {
      e.preventDefault();
      this.classList.add('dragging');
    };
    this.ondragleave = e => {
      if (!this.contains(e.relatedTarget)) this.classList.remove('dragging');
    };
    this.ondrop = e => {
      e.preventDefault();
      this.classList.remove('dragging');
      if (e.dataTransfer.files.length) handleFiles(e.dataTransfer.files);
    };

    return [
      button({ type: 'button', class: 'drop-area',
        onclick: () => this.querySelector('input').click()
      },
        span({ class: 'drop-text' }, 'Drop files here'),
        span({ class: 'drop-hint' }, 'or click to select')
      ),
      input({ type:'file', multiple:true, accept, hidden:true,
        onchange(e) {
          if (e.target.files.length) {
            handleFiles(e.target.files);
            e.target.value = '';
          }
        }
      })
    ];
  }
});

let status = dom.p({ role: 'status' });
document.body.render(
  mx.dropZone({
    accept: 'image/*',
    ondrop(files) { status.textContent = 'Selected: ' + files.map(f => f.name).join(', '); }
  }),
  status
);
Key pattern

Drag events are assigned directly on this (this.ondragover, this.ondrop, etc.) because they need to be on the component element itself. Direct assignment is safe on re-render - it overwrites the previous handler instead of stacking listeners. The visual content is returned as mx children.

Computed attributes#

Components can compute derived values from props and set attributes on themselves via this.$attrs(). This progress bar calculates the completion percentage and an urgency level, and sets attributes the CSS can target:

JSRunnablePlayground
define('goal-progress', {
  $({ pledged = 0, goal = 1000, deadline }) {
    let pct = Math.min(100, Math.round(pledged / goal * 100));
    let days = deadline
      ? Math.ceil((new Date(deadline) - Date.now()) / 86400000)
      : null;

    // Set attributes for CSS styling
    this.$attrs({
      completed: pct >= 100 || null,
      urgency: days !== null && days <= 3 ? 'high'
             : days !== null && days <= 7 ? 'medium'
             : null
    });

    return [
      mx.div({ class: 'bar' },
        mx.div({ class: 'fill', style: `width:${pct}%` })
      ),
      mx.div({ class: 'stats' },
        mx.div(mx.strong('$' + pledged.toLocaleString()),
          ' of $' + goal.toLocaleString()),
        days !== null
          ? mx.div(mx.strong(days), ' days to go')
          : null,
        mx.div(mx.strong(pct + '%'), ' funded')
      )
    ];
  }
});

document.body.render(
  mx.goalProgress({
    pledged: 30000, goal: 50000,
    deadline: Date.now() + 5 * 86400000   // five days out: urgency="medium"
  })
);
$attrs for CSS hooks

this.$attrs({ urgency: "high" }) sets urgency="high" on the element. Your CSS can then target goal-progress[urgency="high"] for styling. Passing null or false removes the attribute. This is cleaner than toggling class names manually.