Modules: Styles, properties, attributes, and events
🎯 Introduction
The virtual nodes we created in the previous article describe page structure, but do not yet apply styles or bind events. In this article, we will learn Snabbdom's module system and six common modules that let virtual nodes describe a complete interface.
🧱 Why modules?
Snabbdom has a very small core focused on sel, text, children, and key. What about classes, styles, and events? These features are implemented as modules that you register as needed.
Think of a phone: the core is the device, and you install apps for photography, games, and other capabilities. Register modules with init:
import {
init,
h,
classModule,
propsModule,
attributesModule,
datasetModule,
styleModule,
eventListenersModule
} from 'snabbdom';
const patch = init([
classModule, // Classes
propsModule, // DOM properties
attributesModule, // HTML attributes
datasetModule, // data-* attributes
styleModule, // Inline styles
eventListenersModule // Event listeners
]);
Once registered, the modules handle the corresponding fields in data, the second argument to h. A field has no effect if its module is not registered, a common source of confusion for beginners.
🎨 The class and style modules
The class module controls classes with an object whose keys are class names and whose values are booleans:
const vnode = h(
'div.card',
{
class: { active: true, hidden: false }
},
'Card'
);
Rendered result:
<div class="card active">Card</div>
Set active to false during an update, and Snabbdom removes that class without affecting the others.
The style module sets inline styles using an object with camelCase property names:
const vnode = h(
'div',
{
style: { color: 'red', fontSize: '20px' }
},
'Red text'
);
Rendered result:
<div style="color: red; font-size: 20px;">Red text</div>
delayed styles, applied after an element is inserted. Combined with CSS transition, these can produce entrance animations. This is an advanced feature; knowing it exists is enough for now.⚖️ props versus attrs (important)
These two modules are easy to confuse. Keep their roles clear:
| Module | data field | How it works | Reflected in the HTML tag? |
|---|---|---|---|
| propsModule | props | Sets DOM object properties directly | Not always |
| attributesModule | attrs | Sets HTML attributes using setAttribute | Yes |
Compare these examples:
// props: set DOM properties.
h('input', { props: { value: 'hello' } });
// Result: <input>. There is no value attribute, but the input displays a value.
// attrs: set HTML attributes.
h('input', { attrs: { value: 'hello', placeholder: 'Enter a value' } });
// Result: <input value="hello" placeholder="Enter a value">
Which should you use?
- Use
propsfor DOM state, including form values (value,checked) anddisabled. - Use
attrsfor HTML attributes such asplaceholder,title, anddata-*.
📦 The dataset and event listener modules
The dataset module sets custom data-* attributes, automatically converting keys to kebab-case:
h(
'div',
{
dataset: { action: 'reset', userId: 100 }
},
'Content'
);
// Result: <div data-action="reset" data-user-id="100">Content</div>
The event listener module binds events through the on field:
const vnode = h(
'button',
{
on: {
click: () => alert('Clicked')
}
},
'Click me'
);
A useful benefit: Snabbdom automatically removes obsolete event listeners when nodes are updated or removed. You do not need to unbind them manually, helping prevent memory leaks.
🛠 Putting it together
Combine several modules to render an interactive card:
const vnode = h(
'div.card',
{
class: { active: true },
style: { backgroundColor: '#f5f5f5', padding: '20px' },
dataset: { id: 1 },
attrs: { title: 'Hover tooltip' },
on: { click: () => console.log('Card clicked') }
},
'A complete card'
);
patch(document.getElementById('app'), vnode);
One object describes the structure, styles, data, and behavior. That is the appeal of the virtual DOM.
❓ Questions and answers
Q1: Does using style without registering the style module throw an error?
No, but the styles have no effect. If the page looks different from what you expect, first check that the module is registered.
Q2: Does the class module conflict with .box in the selector?
No. Both contribute classes to the element. Use the selector for fixed classes and the class module for classes that toggle dynamically.
Q3: Can on bind custom events?
Yes. It uses addEventListener underneath, so it supports both native and custom events.
Q4: Can I bind multiple handlers to the same event?
Yes. Use an array: on: { click: [fn1, fn2] }. The handlers run in order when the event fires.
🧪 Exercise
Render a button with the initial text "Follow". When clicked, it should display "Following", gain the active class, and have a gray background.
import { init, h, classModule, styleModule, eventListenersModule } from 'snabbdom';
const patch = init([classModule, styleModule, eventListenersModule]);
// Write your code here. Hint: create a new vnode and call patch on click.
🎉 You now understand Snabbdom's module system! Next, we will explore patch and the complete rendering and update process.
The h function
Learn common h function signatures, selector syntax, and virtual node fields, and describe pages with nested children.
Rendering and updates with patch
Learn the two forms of patch, how initial rendering replaces the container, and the two update paths, and avoid reusing the original container.
