Introduction
BlokJS is a zero-build, zero-dependency, standalone, reactive, lightweight UI framework. ~8 KB gzipped - just a script tag and plain JavaScript objects that describe your UI. State is reactive via ES Proxy - when data changes, only the affected DOM bindings update. Components, routing, stores, and async tracking are all built in.
See the Full Example: Task Board for a complete single-file app that exercises every feature.
Using an LLM to write BlokJS code? Include the LLM Reference (~4,700 tokens) in your context for best results.
Browser Support
BlokJS targets ES2020 and uses modern browser APIs. No polyfills or legacy fallbacks are included. The core dependency (ES Proxy) has 96%+ global browser support per caniuse.com.
| Browser | Minimum Version |
|---|---|
| Chrome | 91+ |
| Edge | 91+ |
| Firefox | 88+ |
| Safari | 14.1+ |
| Internet Explorer | Not supported |
Required APIs
The framework relies on these modern JavaScript features:
| API | Used For | Chrome | Firefox | Safari |
|---|---|---|---|---|
| ES Proxy / Reflect | Core reactivity system | 49+ | 18+ | 10+ |
| WeakMap / Set / Symbol | Dependency tracking and internal references | 36+ | 6+ | 9+ |
queueMicrotask | Batched DOM updates | 71+ | 69+ | 12.1+ |
globalThis | Environment detection | 71+ | 65+ | 12.1+ |
structuredClone is used for deep cloning state and store data when available (Safari 15.4+, Chrome 98+), but is not required - the framework falls back to a shallow copy on older browsers.
Quick Start
CDN (No Build Step)
Include BlokJS from a CDN and write your app in a single HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/@maleta/blokjs/dist/blokjs.min.js"></script>
</head>
<body>
<div id="app"></div>
<script>
blok.mount('#app', {
state: { count: 0 },
methods: {
inc() { this.count++ },
dec() { this.count-- },
},
view: ($) => ({
div: { children: [
{ h1: { text: $.count } },
{ button: { click: 'dec', text: '-' } },
{ button: { click: 'inc', text: '+' } },
] }
})
})
</script>
</body>
</html>The CDN script exposes a global blok object with component, store, and mount methods. State is reactive - when count changes, the bound h1 updates automatically.
The vanilla approach gives you full control over loading. You can split components across separate files and load them on demand - no bundler decides what ships in your initial payload:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@maleta/blokjs/dist/blokjs.min.js"></script>
<!-- Deferred scripts load in parallel but execute after HTML is parsed -->
<script src="/components/admin-panel.js" defer></script>
</head>
<body>
<div id="app"></div>
<script defer>
blok.mount('#app', {
view: () => ({ 'admin-panel': {} })
})
</script>
</body>
</html>// components/admin-panel.js
blok.component('AdminPanel', {
state: { users: [] },
mount() {
fetch('/api/users')
.then(r => r.json())
.then(data => { this.users = data })
},
view: ($) => ({
div: { children: [
{ h2: { text: 'Admin Panel' } },
{ ul: { children: $.users.map(u => ({ li: { text: u.name } })) } },
] }
})
})The defer attribute tells the browser to download the script in parallel while parsing HTML, then execute it - in source order - once the document is fully parsed. This means admin-panel.js registers the component before blok.mount runs, with zero render-blocking.
Vite (Build Tool)
For larger projects, use the Vite plugin for auto-discovery, bundling, and HMR. See Using with Vite.
Want to see every feature in one place? Jump to the Task Board →
Using with Vite
While BlokJS works without a build step, the Vite plugin adds conveniences for larger projects: automatic component and store registration from file directories, bundling everything into optimized output, and hot module replacement during development.
Scaffold a new project in one command:
npm create blokjs my-app
cd my-app
npm install
npx viteManual Setup
Add to an existing Vite project:
npm install blokjs vite-plugin-blokjsProject structure:
my-app/
index.html
main.js
vite.config.js
components/
counter.js
stores/
app.js<!-- index.html -->
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
<div id="app"></div>
<script type="module" src="/main.js"></script>
</body>
</html>// vite.config.js
import { defineConfig } from 'vite'
import { blokjs } from 'vite-plugin-blokjs'
export default defineConfig({
plugins: [blokjs()],
})// main.js
import { mount } from '@maleta/blokjs'
import 'virtual:blokjs'
mount('#app', {
view: ($) => ({ counter: {} }),
})Dev Server & Production Build
npx vite # dev server with HMR
npx vite build # bundle to dist/
npx vite preview # preview the production buildAuto-Registration
The plugin scans components/ and stores/ directories, registering each file by its filename. Files prefixed with _ are ignored.
components/counter.js -> component('counter', ...)
stores/app.js -> store('app', ...)
components/_helper.js -> ignoredComponent and store files use default exports:
// components/counter.js
export default {
state: { count: 0 },
methods: {
increment() { this.count++ },
decrement() { this.count-- },
},
view: ($) => ({
div: { children: [
{ h1: { text: $.count } },
{ button: { click: 'decrement', text: '-' } },
{ button: { click: 'increment', text: '+' } },
] },
}),
}Plugin Options
blokjs({
componentsDir: 'components', // default
storesDir: 'stores', // default
})Using with PocketBase
The @maleta/blokjs-pocketbase package turns a PocketBase collection into a BlokJS store. Records load into items and follow realtime changes. Every method gets loading and error tracking like any async store method. pbAuth does the same for the signed-in user. The app supplies the PocketBase SDK client.
<script src="https://cdn.jsdelivr.net/npm/@maleta/blokjs/dist/blokjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/pocketbase@0.28/dist/pocketbase.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@maleta/blokjs-pocketbase/dist/blokjs-pocketbase.min.js"></script>const pb = new PocketBase('/')
blok.store('todos', blokPocketbase.pbCollection(pb, 'todos', { sort: '-created' }))
blok.mount('#app', {
mount() { this.store.todos.connect() },
methods: {
add() { this.store.todos.save({ title: 'New todo' }) },
toggle(todo) { this.store.todos.save({ id: todo.id, done: !todo.done }) },
remove(todo) { this.store.todos.remove(todo.id) },
},
view: ($) => ({ div: { children: [
{ button: { click: 'add', text: 'Add' } },
{ when: $.store.todos.loading.connect, children: [{ p: 'Loading...' }] },
{ each: $.store.todos.items, as: 'todo', key: 'id', children: [
{ p: { text: $.todo.title, click: 'toggle(todo)' } },
] },
] } }),
})pbCollection(pb, name, options)
| Member | Description |
|---|---|
items | The records, in sort order |
load() | Fetch all matching records into items |
connect() | load(), then apply realtime creates, updates and deletes until disconnect() |
disconnect() | Stop following realtime changes |
save(data) | Update when data.id is set, otherwise create. Returns the saved record |
remove(id) | Delete the record |
Options: filter, sort, expand and fields pass through to PocketBase. key names a field with a unique index, so save() without an id updates the record with the same key instead of failing.
pbAuth(pb, options)
| Member | Description |
|---|---|
user | The signed-in record (a copy), or null |
isLoggedIn | Computed: user !== null |
connect() | Validate a saved session with the server and follow auth changes from anywhere, including other tabs |
login(identity, password) | Password login against options.collection (default users) |
logout() | Clear the session |
Create collections with a PocketBase migration or the admin UI. Serve the app from PocketBase's pb_public directory so the page and the API share an origin. See examples/pocketbase for a runnable app.
Prerender & Hydration
A BlokJS page renders in the browser, so clients that do not run JavaScript (crawlers other than Google, link previews, payment provider site reviews, curl) see an empty mount node. Prerendering writes the rendered HTML into the page as a build step. The app keeps working without that step; it only adds HTML for those clients.
bunx blokjs-prerender index.html
bunx blokjs-prerender index.html --routes / /about --out dist
bunx blokjs-prerender index.html --inline --out distThe CLI runs the scripts of the page (inline, local files and module scripts) with a server build of blok, renders every blok.mount() call, and writes the HTML into the mount node together with a data-blok-ssr attribute. Without --routes it renders every route that has no :param, no wildcard and no guard. The route /about is written to about.html, which static hosts serve at /about. Without --out the page is updated in place, and running it again replaces the earlier output.
With --inline, every output file is self-contained: local scripts and stylesheets are minified and embedded, and the blokjs script tag is replaced by the runtime that rendered the HTML, so the two always match. Remote scripts and stylesheets stay external, and images and fonts are not copied. --inline needs --out, so the source page stays as it is.
In the browser, blok.mount() sees data-blok-ssr and adopts the existing nodes instead of creating new ones. Nothing is duplicated or flashes, and focus, scroll position, iframes and text typed before the script loaded are kept. When the HTML does not match the view, mount() renders fresh, and development builds log where the difference is.
renderToString(opts, options)
Servers and custom build scripts get the same HTML from the server entry. It runs the regular renderer against a small built-in DOM, with no browser and no dependencies.
import { component, renderToString } from '@maleta/blokjs/server'
component('Hello', { props: ['name'], view: ($) => ({ h1: $.name }) })
const html = renderToString({
state: { who: 'world' },
view: ($) => ({ Hello: { name: $.who } }),
}, { url: '/' })
// <div id="app" data-blok-ssr>${html}</div>Limits
- mount() and unmount() hooks, route guards and event handlers do not run on the server. Data loaded in mount() is not in the HTML; the page shows what the view shows before that data arrives.
- Page scripts must not touch the DOM at the top level; move that code into mount(). localStorage returns null during prerendering. CDN scripts other than blokjs, and module scripts that import remote URLs, are not evaluated.
- Without --inline, pin the blokjs version in the CDN URL. A cached older runtime appends to the prerendered HTML instead of adopting it, which shows the content twice.
- Keep HTML comments in the output: they mark when and each blocks. A minifier that strips comments makes every page render fresh.
- Markup that the HTML parser restructures cannot be adopted, for example tr directly inside table, or block elements inside p. renderToString warns about these.
blok.component(name, def)
Registers a reusable component. The name should start with an uppercase letter - lowercase names are treated as HTML elements, not components.
blok.component('UserCard', {
props: ['name', 'email'],
view: ($) => ({
div: { class: 'card', children: [
{ h3: { text: $.name } },
{ p: { text: $.email } },
] }
})
})Components are used in templates by name:
{ UserCard: { name: 'Alice', email: 'alice@example.com' } }Definition Shape
| Property | Type | Description |
|---|---|---|
props | string[] | Property names the component accepts from its parent |
state | Record<string, any> | Initial reactive state (deep cloned via structuredClone when available, shallow copy otherwise) |
computed | Record<string, fn> | Derived getter functions. Not cached - re-evaluates on every read |
watch | Record<string, fn | { handler, deep, immediate }> | Watchers for state, prop, computed, store or route paths. Receives (newVal, oldVal) |
methods | Record<string, fn> | Instance methods. Async methods get automatic loading/error tracking |
mount | fn | Called after the component is inserted into the DOM |
unmount | fn | Called when the component is destroyed |
view | ($) => object | Returns a template object describing the UI. Required |
Only view is required. All other properties are optional.
blok.mount(target, opts)
Mounts the root application onto a DOM element. Returns an object with a destroy() method.
const app = blok.mount('#app', {
state: { count: 0 },
view: ($) => ({ div: { text: $.count } })
})
// Tear down later
app.destroy()The target can be a CSS selector string or an HTMLElement. After destroy(), all component and store registrations are lost - re-register them before mounting again.
Multiple Mounts
Multiple blok.mount() calls create independent app instances. By default they share the global component registry and store state:
// Shared (default) - both see the same stores and components
blok.mount('#app1', { view: ($) => ({ MyWidget: {} }) })
blok.mount('#app2', { view: ($) => ({ MyWidget: {} }) })
// Isolated - own store state, copied component registry
blok.mount('#sidebar', {
isolated: true,
view: ($) => ({ Nav: {} })
})When the target has the data-blok-ssr attribute, mount() adopts the HTML already inside it instead of rendering it again. See Prerender & Hydration.
Root-Only Options
blok.mount() accepts all component definition options (props, state, computed, watch, methods, mount, unmount, view) plus these root-only options:
| Option | Type | Description |
|---|---|---|
routes | RouteConfig[] | Route definitions for client-side routing |
guards | Record<string, fn> | Named route guard functions |
mode | 'hash' | 'history' | 'auto' | Router mode (default: 'auto'). 'auto' uses hash for file:// URLs, history otherwise |
isolated | boolean | When true, creates a fully sandboxed instance with its own store state and a copied component registry |
blok.store(name, def)
Registers a named store with structured state, computed properties, and methods, and returns the store. Call before blok.mount(). Calling blok.store() with an already-registered name logs a warning, skips the duplicate and returns the existing store.
blok.store('auth', {
state: { user: null, token: null },
computed: {
isLoggedIn() { return this.user !== null }
},
methods: {
logout() { this.user = null; this.token = null },
async login(email, password) {
const res = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
})
const data = await res.json()
this.user = data.user
this.token = data.token
}
}
})| Property | Type | Description |
|---|---|---|
state | Record<string, any> | Initial reactive state (deep cloned via structuredClone when available, shallow copy otherwise) |
computed | Record<string, fn> | Derived values. this refers to the store proxy. |
methods | Record<string, fn> | Actions. this refers to the store proxy. Async methods get automatic loading/error tracking. Store methods cannot access other stores via this — use component methods for cross-store interaction. |
Accessing Stores
// In methods / lifecycle
this.store.auth.user // state
this.store.auth.isLoggedIn // computed
this.store.auth.login(e, p) // method
// In templates
{ span: { text: $.store.auth.user.name } }
{ when: $.store.auth.isLoggedIn, children: [...] }Store Loading & Error
Async store methods automatically get loading and error tracking (same pattern as component async methods):
// In templates
{ when: $.store.auth.loading.login, children: [
{ p: 'Signing in...' }
] }
{ when: $.store.auth.error.login, children: [
{ p: { class: 'error', text: $.store.auth.error.login } }
] }
// In methods
this.store.auth.loading.login // true while running
this.store.auth.error.login // rejection value (typically Error) or nullUsing Stores Outside Components
blok.store(name, def) returns the store, the same object shared mounts see as this.store[name]. blok.store(name) with one argument looks up a registered store and returns undefined for an unknown name.
store.$state holds the state keys only, without computed values, methods, loading or error, so JSON.stringify, Object.keys and spread work on it. Assigning an object writes each of its keys, like Object.assign; keys missing from it stay unchanged. $state is a reserved name, so do not use it as a state key. A state key named loading or error is shadowed by async tracking: store.error is the per-method error map, so read the key as store.$state.error.
const auth = blok.store('auth')
JSON.stringify(auth.$state) // '{"user":null,"token":null}'
auth.$state = { user, token } // the view and computed values update
const stop = blok.watch(
() => auth.$state,
(state, oldState) => localStorage.setItem('auth', JSON.stringify(state)),
{ deep: true }
)
stop() // ends the watch| Option | Description |
|---|---|
deep | Track every nested key and index. push, splice, a nested set, and adding or deleting a key call back once per batch, even though the value is the same object. |
immediate | Call back once right away, with undefined as the old value. |
blok.watch(getter, callback, options) tracks the getter like a computed and runs the callback in the same microtask batch as other updates. Without deep, the callback runs only when the getter returns a different value (===). The watch lives until stop() is called. In @maleta/blokjs/server it does nothing.
Context (this)
Inside methods, computed, watch, and lifecycle hooks, this provides access to:
| Property | Description |
|---|---|
this.<state> | Read/write local state properties |
this.<computed> | Read computed values |
this.<method>() | Call methods |
this.<prop> | Read props passed by parent |
this.store | Access named stores via this.store.<name> (read/write) |
this.loading | Reactive loading state for async methods - this.loading.<method> is true while running |
this.error | Reactive error state for async methods - this.error.<method> holds the Error or null |
this.route | { path, params, query } - current route info |
this.refs | Object of named DOM element references |
this.el | The component's root DOM element |
this.emit(event, payload?) | Emit an event to the parent component |
this.navigate(to) | Navigate to a path (string) or history offset (number) |
methods: {
save() {
this.store.myStore.items.push({ name: this.name }) // write to store
this.name = '' // write to state
this.emit('saved') // notify parent
this.navigate('/') // go to home
this.refs.input.focus() // access DOM
console.log(this.route.params.id) // read route
console.log(this.total) // read computed
}
}Props
An array of property names the component accepts from its parent.
blok.component('Badge', {
props: ['label', 'color'],
view: ($) => ({
span: {
class: 'badge',
style: { backgroundColor: $.color },
text: $.label,
}
})
})
// Usage
{ Badge: { label: 'New', color: '#f59e0b' } }Props passed as $ refs are reactive — changes in the parent automatically update the child. Writing to a prop in the child writes back to the parent.
State
Initial local reactive state. Each component instance gets a deep clone (via structuredClone when available, shallow copy otherwise). If state contains non-cloneable values (functions, DOM elements), a shallow copy is used instead.
state: { count: 0, items: [], filter: '' }Access and modify state on this inside methods, computed, watch, and lifecycle hooks:
methods: {
add() {
this.items.push({ name: this.newItem })
this.newItem = ''
}
}Computed
Derived getter functions. Computed values are lazy and memoized - they only re-evaluate when a tracked dependency changes, and cache the result until then.
computed: {
filtered() {
return this.items.filter(i => i.name.includes(this.filter))
},
total() {
return this.items.length
}
}Access computed values like state: this.total or in templates via $.total.
Watch
React to state, prop, or computed changes. The key is a property name or dot-notation path to watch.
watch: {
filter(newVal, oldVal) {
console.log(`filter changed: ${oldVal} -> ${newVal}`)
},
count(val) {
if (val > 100) this.count = 100
},
// Dot-notation paths work for nested state, store, and route
'route.path'(newPath) {
console.log('navigated to', newPath)
},
'store.auth.user'(user) {
console.log('auth user changed', user)
}
}To trigger a watcher on nested changes, reassign the top-level value:
methods: {
updateUserName(name) {
// Won't trigger the 'user' watcher:
this.user.name = name
// Will trigger the 'user' watcher:
this.user = { ...this.user, name }
}
}The object form takes options beside the handler. With deep, any nested change calls the handler, including push, a nested set and adding or deleting a key. With immediate, the handler runs once when the component is set up, with undefined as the old value.
watch: {
'store.todos.items': {
handler(items) { localStorage.setItem('todos', JSON.stringify(items)) },
deep: true,
immediate: true
}
}Watchers are best for side effects (API calls, localStorage sync). For derived values that depend on multiple properties, use computed instead.
Methods
Instance methods. The this context gives access to state, computed, store, and other methods. See Context for the full list.
methods: {
add() {
if (!this.newText.trim()) return
this.items.push({ text: this.newText.trim(), done: false })
this.newText = ''
},
remove(item) {
this.items = this.items.filter(i => i !== item)
}
}Methods are referenced by name in event handlers: { click: 'add' }
Async Methods
Methods that return a Promise automatically get reactive loading and error state. No extra boilerplate needed.
state: { users: [] },
methods: {
async fetchUsers() {
const res = await fetch('/api/users')
this.users = await res.json()
}
}
// Automatic reactive state:
// this.loading.fetchUsers → true while running, false after
// this.error.fetchUsers → Error if thrown, null otherwiseIn Templates
// Show loading state
{ when: $.loading.fetchUsers, children: [
{ p: 'Loading...' }
] }
// Show error
{ when: $.error.fetchUsers, children: [
{ p: { class: 'error', text: $.error.fetchUsers } }
] }
// Show content when not loading
{ when: $.not.loading.fetchUsers, children: [
{ ul: { children: [
{ each: $.users, as: 'user', children: [
{ li: { text: $.user.name } }
] }
] } }
] }Behavior
When a method returns a Promise: loading[name] is set to true (immediately when the method returns a Promise), then false on resolve or reject. On rejection, error[name] is set to the Error object. On the next call, error[name] resets to null.
Lifecycle
| Hook | Signature | Description |
|---|---|---|
mount | mount() | Called after the component is inserted into the DOM |
unmount | unmount() | Called when the component is destroyed |
mount() {
this.interval = setInterval(() => this.count++, 1000)
},
unmount() {
clearInterval(this.interval)
}mount runs asynchronously via microtask - the component is already in the DOM but the call is deferred. This means DOM measurements (element sizes, scroll positions) are reliable, but this.route may not yet reflect the initial route during the very first mount.
Both hooks have full access to the this.* context including state, store, refs, and methods.
View Function
The view function receives the $ proxy and returns a template object. Called once — reactivity is handled by the refs.
view: ($) => ({
div: { class: 'container', children: [
{ h1: { text: $.title } },
{ p: { text: $.description } },
{ button: { click: 'save', text: 'Save' } },
] }
})The returned object describes a single root element. Nest via children arrays. The view function is the only required property in a component definition — everything else is optional.
View DSL ($)
Creating Refs
The $ parameter in the view function is a Proxy. Property access creates reactive references (BlokRef) that are resolved at render time.
view: ($) => {
$.count // ref to this.count (state/prop/computed)
$.store.auth.user // ref to this.store.auth.user
$.item.name // ref to iteration variable 'item', property 'name'
return { div: { text: $.count } }
}Negation
$.not creates a negated ref. The resolved value is !value.
{ when: $.not.loading, children: [
{ p: 'Content loaded!' }
] }
{ button: { disabled: $.not.canSubmit, text: 'Submit' } }
// $.not only works at the start of the path
$.not.active // !this.active
$.not.store.auth.isLoggedIn // !this.store.auth.isLoggedIn
// This does NOT work:
$.store.not.ready // 'not' becomes a property name, not negationIteration Variables
Inside an each block, the as name becomes a ref on $:
{ each: $.todos, as: 'todo', children: [
{ span: { text: $.todo.text } },
{ input: { type: 'checkbox', model: $.todo.done } },
] }
// Default iteration variable name is 'item'
{ each: $.items, children: [
{ li: { text: $.item } }
] }Elements
A template object's key is the HTML tag name. The value defines its content.
{ div: 'Hello' } // <div>Hello</div>
{ div: { class: 'box' } } // <div class="box"></div>
{ br: true } // <br>
{ input: { type: 'text' } } // <input type="text">
{ div: 42 } // <div>42</div>
// Custom elements / web components work too
{ 'my-widget': { class: 'fancy', text: $.data } } // <my-widget class="fancy">...</my-widget>
{ 'sl-button': { variant: 'primary', text: 'Click' } } // <sl-button variant="primary">Click</sl-button>Each object describes exactly one element, so it has exactly one tag key. Siblings go in children. Conditionals and loops are their own node shapes ({ when, children } and { each, as, key, children }) and never sit next to a tag key. Development builds warn about any other shape.
{ div: 'a', button: 'b' } // wrong: only the div renders
{ when: $.ok, button: 'b' } // wrong: when is ignored
{ div: { children: [{ div: 'a' }, { button: 'b' }] } }
{ button: { when: $.ok, text: 'b' } }
{ when: $.ok, children: [{ button: 'b' }] }Text
| Key | Description |
|---|---|
text | Text content. Static string or reactive ref. |
// Static text
{ p: { text: 'Hello World' } }
// Reactive text
{ h1: { text: $.title } }
// Mixed: static text + reactive child
{ p: { text: 'Count: ', children: [
{ span: { text: $.count } }
] } }
// Or use a computed for cleaner interpolation
// computed: { countLabel() { return `Count: ${this.count}` } }
{ p: { text: $.countLabel } }
// Shorthand: ref as the element value
{ span: $.count } // equivalent to { span: { text: $.count } }HTML
html sets raw HTML on the element using innerHTML.
// Static HTML
{ div: { html: '<b>Bold</b> and <em>italic</em>' } }
// Reactive HTML
{ div: { html: $.richContent } }Children
An array of child template objects, rendered in order.
{ ul: { children: [
{ li: 'First' },
{ li: 'Second' },
{ li: { text: $.third } },
] } }
// Strings in children become text nodes
{ p: { children: ['Hello ', { b: 'World' }] } }Classes
Multiple ways to set CSS classes:
// String
{ div: { class: 'box large' } }
// Reactive string
{ div: { class: $.className } }
// Conditional object — keys are class names, values are booleans or refs
{ li: { class: { active: $.isActive, done: $.todo.done } } }
// Array (mixed string + conditional)
{ div: { class: ['base', { highlight: $.isNew }] } }
// Kebab-case class names — quote the key
{ div: { class: { 'is-active': $.isActive, 'has-error': $.hasError } } }
// Function form - same $ as function-form when, loop variables included
{ each: $.groups, as: 'grp', key: 'name', children: [
{ button: { class: { tab: true, active: ($) => $.grp.name === $.activeGroup }, text: $.grp.name } }
] }Styles
Inline styles as a string or an object. Object keys use camelCase, converted to kebab-case.
// String
{ div: { style: 'color: red; font-size: 14px' } }
// Object
{ div: { style: { color: 'red', fontSize: '14px' } } }
// Reactive values
{ div: { style: { backgroundColor: $.bgColor, opacity: $.fade } } }Attributes
Any key that is not a reserved name or event name is treated as an HTML attribute.
// Static
{ input: { type: 'text', placeholder: 'Enter name' } }
{ img: { src: '/logo.png', alt: 'Logo' } }
{ a: { href: '/about', target: '_blank', text: 'About' } }
// Reactive — pass a ref directly for single attributes
{ input: { disabled: $.not.enabled } } // reactive boolean
// bind groups reactive attributes (optional — direct refs work too)
{ img: { bind: { src: $.imageUrl, alt: $.title } } }
// Equivalent — refs work directly as attribute values
{ img: { src: $.imageUrl, alt: $.title } }
// Boolean attributes
{ button: { disabled: true } } // <button disabled>
{ button: { disabled: false } } // <button> (removed)Properties
Attributes are always strings. props assigns JavaScript properties instead: arrays and objects for web components, or properties that have no attribute, such as indeterminate.
// Static values or refs - a ref re-assigns the property when its value changes
{ 'data-grid': { props: { rows: $.rows, columns: $.columns } } }
{ input: { type: 'checkbox', props: { indeterminate: $.partial } } }
// Functions are assigned as-is, e.g. callbacks the element calls
{ 'data-grid': { props: { renderCell: formatCell } } }Model
Two-way binding between a form element and a reactive ref.
// Text input — binds .value, listens to 'input' event
{ input: { type: 'text', model: $.name } }
// Checkbox — binds .checked, listens to 'change' event
{ input: { type: 'checkbox', model: $.agreed } }
// Select — binds .value, listens to 'change' event
{ select: { model: $.category, children: [
{ option: { value: '', text: 'All' } },
{ option: { value: 'books', text: 'Books' } },
{ option: { value: 'music', text: 'Music' } },
] } }
// Textarea — binds .value, listens to 'input' event
{ textarea: { model: $.content } }
// Custom elements - bind .value, listen to 'input' event
{ 'wa-input': { model: $.email } }
// Other shapes (e.g. a switch with .checked): props + on
{ 'wa-switch': { props: { checked: $.dark }, on: { change: 'toggleDark' } } }Events
Events are specified as string values — either a method name or an assignment expression.
// Call a method (receives the native Event as argument)
{ button: { click: 'handleClick', text: 'Click' } }
// Same, as a method ref
{ button: { click: $.handleClick, text: 'Click' } }
// Inline state assignment
{ button: { click: 'editing = true', text: 'Edit' } }
{ button: { click: 'count = 0', text: 'Reset' } }
// Form submit (e.preventDefault() is called automatically)
{ form: { submit: 'save', children: [...] } }
// Pass arguments to methods
{ button: { click: 'remove(item)', text: 'x' } }
{ button: { click: 'select(item.id)', text: 'Go' } }
{ button: { click: 'update(item, true)', text: 'Save' } }
// Multiple events via 'on' object
{ input: { on: { focus: 'onFocus', blur: 'onBlur' } } }A method ref ($.handleClick) is the same as the string 'handleClick' and works everywhere a handler string does. Refs cannot be called, so $.remove(item) does not work: use the string form 'remove(item)' for arguments and assignments.
Recognized Event Names
These events can be used as direct keys on element options:
click, dblclick, mousedown, mouseup, mousemove,
mouseenter, mouseleave, keydown, keyup, keypress,
input, change, submit, focus, blur, scroll, resize,
touchstart, touchend, touchmove,
dragstart, dragend, dragover, dragleave, dropFor other events, including custom events from web components, use the on object.
{ 'wa-dialog': { on: { 'wa-after-hide': $.onClose } } }Argument Passing
Pass arguments to method calls using function-call syntax. Arguments are resolved at event time.
// Iteration variable
{ each: $.items, as: 'item', key: 'id', children: [
{ button: { click: 'remove(item)', text: 'x' } }
]}
// Nested path
{ button: { click: 'select(item.id)' } }
// Literals: strings, numbers, booleans, null
{ button: { click: "log('clicked')" } }
{ button: { click: 'setPage(1)' } }
{ button: { click: 'toggle(true)' } }
// Multiple arguments
{ button: { click: 'update(item, true, 42)' } }Assignment Expressions
Supported value types in assignment expressions:
'count = 0' // number
'active = true' // boolean
'active = false' // boolean
'name = null' // null
"name = ''" // empty string
"name = 'hello'" // stringEvent Modifiers
Use object syntax or dot-separated modifiers to automatically call preventDefault() or stopPropagation():
// Object syntax (recommended)
{ a: { click: { handler: 'navigate', prevent: true }, text: 'Go' } }
{ div: { click: { handler: 'handler', stop: true } } }
{ div: { click: { handler: 'handler', prevent: true, stop: true } } }
{ div: { click: { stop: true } } } // modifier-only, no handler
// String syntax (also supported)
{ a: { 'click.prevent': 'navigate', text: 'Go' } }
{ div: { 'click.stop': 'handler' } }
{ div: { 'click.prevent.stop': 'handler' } }
// Works with the on object too
{ input: { on: { 'focus.stop': 'onFocus' } } }| Modifier | Effect |
|---|---|
prevent | Calls e.preventDefault() before the handler runs |
stop | Calls e.stopPropagation() before the handler runs |
Conditionals
Standalone when
A when block renders its children only when the condition is truthy. Children are created and destroyed reactively.
{ when: $.isLoggedIn, children: [
{ p: 'Welcome back!' },
{ button: { click: 'logout', text: 'Log out' } },
] }
{ when: $.not.isLoggedIn, children: [
{ a: { href: '/login', text: 'Please log in' } },
] }Conditional Element
Add when inside an element's options to conditionally render that element:
{ div: { when: $.showDetails, class: 'details', children: [
{ p: { text: $.description } },
] } }The element and all its children are created/destroyed based on the condition.
Function Form
For expressions with operators (!, &&, >, etc.), pass a function to when. The function receives the reactive component context as $, with loop variables from enclosing each blocks on top. Dependency tracking is automatic:
{ when: ($) => !$.loading, children: [
{ p: 'Content loaded!' }
] }
{ when: ($) => $.count > 10, children: [
{ p: 'Many items!' }
] }
{ when: ($) => $.isLoaded && $.items.length, children: [
{ p: 'Has items' }
] }
// Works with stores too
{ when: ($) => $.store.auth.isLoggedIn || $.isGuest, children: [
{ p: 'Has access' }
] }
// Element-level
{ div: { when: ($) => $.count > 5, text: 'High count' } }
// Inside each - loop variables are available on $
{ each: $.items, as: 'item', key: 'id', children: [
{ when: ($) => $.item.score > $.threshold, children: [
{ p: { text: $.item.name } }
] }
] }Ref Limitations
When using the ref form (without a function), when only accepts $ paths - not JavaScript expressions. Operators evaluate against the proxy object, not the value:
// These do NOT work with refs:
{ when: !$.loading, ... } // always false (! on a proxy object)
{ when: $.count > 10, ... } // compares proxy > 10, not the value
{ span: { text: $.on ? 'on' : 'off' } } // always 'on' (a proxy object is truthy)
// Use function form instead:
{ when: ($) => !$.loading, ... }
{ when: ($) => $.count > 10, ... }
// Or use $.not for simple negation:
{ when: $.not.loading, ... }
// Ref form works for simple truthy/falsy checks:
{ when: $.items.length, ... } // resolves to the array's length
// For very complex conditions, a computed is still a good option:
computed: {
hasLongNames() {
return this.users.filter(a => a.name.length > 10).length > 10
}
}
{ when: $.hasLongNames, children: [...] }Loops
each iterates over a reactive array. Use as to name the iteration variable (default: 'item'). Use key for stable identity.
{ each: $.todos, as: 'todo', key: 'id', children: [
{ li: { children: [
{ input: { type: 'checkbox', model: $.todo.done } },
{ span: { text: $.todo.text } },
] } }
] }
// Without key (uses index)
{ each: $.items, children: [
{ li: { text: $.item } }
] }
// Nested iteration
{ each: $.groups, as: 'group', children: [
{ div: { children: [
{ h3: { text: $.group.name } },
{ each: $.group.items, as: 'item', children: [
{ span: { text: $.item } },
] },
] } }
] }Components
Use registered component names (uppercase) as tag keys. Pass props and listen to events.
// Pass props (static values or reactive refs)
{ UserCard: { name: $.user.name, email: $.user.email } }
// Listen to child events with on_ prefix
{ TodoItem: { todo: $.item, on_remove: 'handleRemove' } }
{ TodoItem: { todo: $.item, on_remove: $.handleRemove } } // method ref
// Parent method 'handleRemove' is called when child does this.emit('remove', payload)Parent-Child Events
Prefix event names with on_ when using a component. The child emits with this.emit('eventName', payload) and the parent's method is called with the payload.
// Child component
blok.component('ColorPicker', {
methods: {
select(e) {
this.emit('pick', e.target.value)
}
},
view: ($) => ({ input: { type: 'color', change: 'select' } })
})
// Parent
{ ColorPicker: { on_pick: 'handleColor' } }
// Parent method
methods: {
handleColor(color) {
this.store.theme = color
}
}Slots
Components can render children passed by their parent using the slot mechanism.
// Define a component with a slot
blok.component('Card', {
props: ['title'],
view: ($) => ({
div: { class: 'card', children: [
{ h3: { text: $.title } },
{ div: { class: 'card-body', children: { slot: true } } },
] }
})
})
// Use with children (slotted content)
{ Card: { title: 'My Card', children: [
{ p: 'This content goes into the slot.' },
{ button: { text: 'Action' } },
] } }Use children: { slot: true } to mark where slot content is inserted. This is the only case where children is not an array.
Refs
Store a reference to a DOM element for direct access in methods.
view: ($) => ({
div: { children: [
{ input: { ref: 'nameInput', type: 'text', model: $.name } },
{ button: { click: 'focusInput', text: 'Focus' } },
] }
})
// Access the element
methods: {
focusInput() {
this.refs.nameInput.focus()
}
}Router
Client-side routing with path matching, params, guards, and programmatic navigation.
Configuration
blok.mount('#app', {
routes: [
{ path: '/', component: 'Home' },
{ path: '/users', component: 'UserList' },
{ path: '/users/:id', component: 'UserDetail' },
{ path: '*', component: 'NotFound' },
],
view: ($) => ({
div: { children: [
{ div: { route: true } },
] }
})
})| RouteConfig | Type | Description |
|---|---|---|
path | string | URL pattern. Use :name for params. Use * for catch-all. |
component | string | Name of a registered component to render. |
guard | string | Name of a guard function to check before entering. |
Route Outlet
Set route: true on any element to make it a route outlet - a container that renders the component matched by the current route.
view: ($) => ({
div: { children: [
{ nav: { children: [
{ a: { href: '/', link: true, text: 'Home' } },
{ a: { href: '/about', link: true, text: 'About' } },
] } },
{ div: { route: true } },
] }
})When the route changes, the previous component is destroyed and the new one is mounted.
Route Links
Add link: true to an <a> element to enable client-side navigation. Click is intercepted, e.preventDefault() is called, and the router navigates to the href. Only works on <a> elements - silently ignored on other tags.
{ a: { href: '/users/42', link: true, text: 'View User' } }
// Dynamic href
{ a: { bind: { href: $.profileUrl }, link: true, text: 'Profile' } }Params & Query
Route parameters are extracted from the URL and available on this.route.
// Route: { path: '/users/:id', component: 'UserDetail' }
// URL: /users/42
// In the component:
computed: {
user() {
const id = Number(this.route.params.id) // '42'
return this.store.users.find(u => u.id === id)
}
}
// Query string: /search?q=hello
// this.route.query.q === 'hello'this.route is reactive - computed values and bindings that read it update when the route changes.
Guards
Guard functions run before a route is entered. Return true to allow, false to block, or a string to redirect.
blok.mount('#app', {
routes: [
{ path: '/admin', component: 'Admin', guard: 'requireAuth' },
{ path: '/login', component: 'Login' },
],
guards: {
requireAuth(to, from) {
if (!this.store.auth.user) return '/login'
return true
}
},
// ...
})Guards have the same this context as the root component. Both to and from are { path, params, query } objects matching the shape of this.route.
Modes
| Mode | Behavior |
|---|---|
'hash' | Uses URL hash (#/path). Works everywhere including file:// URLs. |
'history' | Uses History API (pushState). Requires server configuration. |
'auto' | Uses hash for file:// protocol, history otherwise. This is the default. |
Programmatic Navigation
// Navigate to a path
this.navigate('/users/42')
// Go back/forward in history
this.navigate(-1) // history.go(-1)
this.navigate(1) // history.go(1)Reactivity
BlokJS uses ES Proxy to track property reads inside effects (bindings, computed, watchers). When a tracked property is written, all dependent effects re-run.
// This computed tracks this.items and this.filter
computed: {
filtered() {
return this.items.filter(i => i.name.includes(this.filter))
}
}
// When either items or filter changes, filtered re-evaluates
// and any UI bound to $.filtered updatesNested objects are lazily wrapped — accessing a.b.c creates proxies as needed.
Array Mutations
These array methods are intercepted and trigger reactive updates:
push, pop, shift, unshift, splice, sort, reversethis.todos.push({ text: 'New', done: false }) // triggers update
this.todos.splice(2, 1) // triggers update
this.todos.sort((a, b) => a.text.localeCompare(b.text)) // triggers update
// Direct assignment also works
this.items = this.items.filter(i => !i.done) // triggers updateBatching
Multiple synchronous state changes are batched into a single DOM update via the microtask queue.
methods: {
reset() {
this.name = ''
this.count = 0
this.items = []
// All three changes result in ONE DOM update
}
}Effects are collected into a Set and flushed in a single microtask, preventing redundant renders.
Full Example: Task Board
The Task Board example is a single HTML file that exercises every BlokJS feature — stores, components, routing, guards, slots, async methods, and more. Use it as a reference for how everything fits together.
Architecture
// Stores
blok.store('auth', { state, computed, methods: { async login(), logout() } })
blok.store('board', { state, computed, methods: { async loadTasks(), addTask(), removeTask(), moveTask(), updateTask() } })
// Components (7)
Login — form with model, ref for focus, async submit, navigate()
Board — search with watch, each + nested loop, modal (when), store async, drag-and-drop
TaskColumn — props, computed, style binding, re-emits child events, empty state (when), drag-and-drop zone
TaskCard — class array (string + ref + conditional), bind: { href }, link, emits, draggable
CardWrapper — props, style binding, { slot: true }
TaskDetail — route :id param, html binding, model on select/textarea/checkbox, editing toggle
NotFound — navigate(-1) back
// Routes
/login — Login
/board — Board (guarded)
/task/:id — TaskDetail (guarded)
* — NotFoundFeature Coverage
| Feature | Where |
|---|---|
blok.mount / component / store | Root + 7 components + 2 stores |
props | TaskColumn, TaskCard, CardWrapper |
state | Login, Board, TaskDetail |
computed | TaskCard, TaskColumn, TaskDetail, both stores |
watch | Board (search → store sync) |
methods (sync + async) | All components, both stores |
mount / unmount | Root (nav redirect + cleanup), Login (focus), Board (load + cleanup) |
text / html | Everywhere / TaskDetail description |
class (string, object, array) | TaskCard, TaskColumn |
style (object) | TaskColumn header, CardWrapper |
model (input, select, textarea, checkbox) | Login, Board, TaskDetail |
events (click, submit, drag*) | Forms, buttons, TaskCard drag, TaskColumn drop zone |
event modifiers (stop, prevent) | Board modal (stop), TaskColumn drag (prevent), TaskDetail (prevent) |
when + $.not + function form | Loading, modal, auth nav, empty states |
each + key + nested | Columns → Tasks |
components + on_ events | TaskCard → TaskColumn → Board |
slots | CardWrapper wraps heading in Board |
ref (DOM) | Login input focus |
bind: {} | TaskCard dynamic href |
routing + :params + guards | 4 routes, requireAuth guard, /task/:id |
link: true + route: true | Nav links, route outlet |
multiple stores | auth + board |
async loading/error | Login submit, Board loadTasks |
programmatic navigation | Login→/board, TaskDetail back, logout→/login |
assignment expressions | showEdit = true, showModal = false |
negated refs ($.not) | Auth nav, loading states |
Validation API
BlokJS includes a validate object with pure functions that check definitions and return an array of warning strings. These run automatically via console.warn in dev builds, but the validate API lets you capture warnings programmatically.
validate.component(name, def)
Validates a component definition. Returns warnings for missing view, unknown keys, state conflicts, and type errors.
const warnings = blok.validate.component('todo-item', {
props: ['label'],
// missing view
})
// ['Component "todo-item" is missing the required "view" function.']validate.mount(opts)
Validates mount options. Same checks as component, plus router-specific validation.
const warnings = blok.validate.mount({
state: { count: 0 },
// missing view
})
// ['Mount options missing the required "view" function.']
// Names from other frameworks get a suggestion
blok.validate.mount({ init() {}, view: ($) => ({ div: 'hi' }) })
// ['Unknown mount option "init" - did you mean "mount"?']validate.store(name, def)
Validates a store definition. Checks for unknown keys.
const warnings = blok.validate.store('auth', {
state: { user: null },
foo: 1,
})
// ['Unknown property "foo" in store "auth". Valid: state, computed, methods']validate.template(tag, opts, methods)
Validates a view template node. Catches typos in template keys and references to undefined event handler methods. Pass the methods object (or undefined) as the third argument.
const warnings = blok.validate.template('button', {
click: 'save',
clss: 'btn',
}, { save() {} })
// ['<button> has "clss" - did you mean "class"?']validate.node(tpl)
Validates the shape of a view node: exactly one tag key, or a when/each node without a tag key. Catches siblings written on one object, when, each or children next to a tag key, and empty nodes.
blok.validate.node({ div: 'a', button: 'b' })
// ['Element node has 2 tag keys (div, button). One node = one element. Put siblings in children.']What Gets Caught
The validator catches the following issues:
- Missing or non-function view
- Unknown definition keys, with suggestions for typos and names from other frameworks (init, mounted, created, setup, destroyed, data, render, template...). Runs in minified builds too.
- State keys conflicting with reserved names (store, route, refs, el, etc.)
- Duplicate keys across state, computed, and methods
- Non-function mount, unmount, methods, computed, or watch entries
- Event handlers referencing undefined methods
- Template key typos (Levenshtein-based suggestions)
- Invalid node shapes: two tag keys on one object, when, each or children next to a tag key, empty nodes
- Invalid router mode values