Getting Started

Installation

CDN

<script src="https://cdn.jsdelivr.net/npm/micra.js/dist/micra.min.js"></script>

This exposes a global Micra object.

npm

npm install micra.js
import * as Micra from "micra.js";

Hello Micra

This example builds a small counter with automatic mounting.

1. Add HTML

<div data-component="counter">
  <h1 data-text="count"></h1>
  <button @click="decrement">-</button>
  <button @click="increment">+</button>
</div>

data-component="counter" tells Micra which component definition to use.

2. Define the component

import * as Micra from "micra.js";

Micra.define("counter", {
  state: { count: 0 },

  increment() {
    this.state.count++;
  },

  decrement() {
    this.state.count--;
  },
});

3. Start Micra

Micra.start();

Micra scans the page for elements with data-component, looks up each registered definition, and mounts them.

Step-by-step flow

When the page starts:

  1. Micra finds <div data-component="counter">.
  2. It looks for a registered counter definition.
  3. It creates a component instance.
  4. It wraps state in a reactive Proxy.
  5. It renders directives like data-text.
  6. It binds DOM events like @click and data-on.

After that, each state assignment triggers a batched re-render.

How auto-mount works

Auto-mount is the default pattern for server-rendered HTML.

<section data-component="dashboard"></section>
<section data-component="billing"></section>
Micra.define("dashboard", { state: {} });
Micra.define("billing", { state: {} });
Micra.start();

Micra.start():

You can also limit the scan to a subtree:

Micra.start(document.getElementById("account-panel")!);

Custom element tags

Since 2.10 every defined component also gets a tag: <micra-counter> works in place of <div data-component="counter"> and needs no Micra.start(). It mounts when it enters the page, however it got there, and tears down when it leaves. This is the recommended root for new code, unless the root has to be a specific element like <form>. See Custom elements.

Direct mount

If you do not want auto-mount, mount directly:

const instance = Micra.mount("#counter", {
  state: { count: 0 },
  increment() {
    this.state.count++;
  },
});

Micra.mount() returns the instance or null if the element is missing.

Debugging

While developing, inspect live components with Micra.debug():

Micra.debug();
// [Micra] 3 live component(s)
//   counter   $el: <div>  state: { count: 5 }
//   dropdown  $el: <div>  state: { open: false, label: "Sort by" }

This prints every mounted component, its root element, and current state to the browser console — useful for checking that components mounted correctly and inspecting state values.