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--;
},
});
statebecomes reactive when the component mounts.- Changing
this.state.countschedules a re-render. @click="increment"calls the matching method on the component instance.
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:
- Micra finds
<div data-component="counter">. - It looks for a registered
counterdefinition. - It creates a component instance.
- It wraps
statein a reactiveProxy. - It renders directives like
data-text. - It binds DOM events like
@clickanddata-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():
- scans a
DocumentorHTMLElementroot - mounts every
[data-component]element it finds - skips elements that are already mounted
- is safe to call multiple times
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.