The h() function constructs an element virtual node from a tag name, properties, and child nodes. It replaces a manually written tree of JavaScript objects with a concise declaration of an HTML-like view. section 3.5 section 3.9
A small h() implementation performs four jobs:
- Accepts a tag, props object, and children array, defaulting to h(tag, {}, []). section 3.5
- Removes null children and converts text children into text virtual nodes. section 3.5
- Returns an object containing tag, props, normalized children, and type: DOM_TYPES.ELEMENT. section 3.5
- Keeps event listeners in props for later programmatic attachment when the virtual node becomes real DOM. section 3.7.2
Representing a login form
h('form', { class: 'login-form', action: 'login' }, [ h('input', { type: 'text', name: 'user' }), h('input', { type: 'password', name: 'pass' }), h('button', { on: { click: login } }, ['Log in']) ]) section 3.7.2
Listing 3.1 The h() function to create element virtual nodes (h.js)
import { withoutNulls } from './utils/arrays'
export const DOM_TYPES = {
TEXT: 'text',
ELEMENT: 'element',
FRAGMENT: 'fragment',
}
export function h(tag, props = {}, children = []) {
return {
tag,
props,
children: mapTextNodes(withoutNulls(children)),
type: DOM_TYPES.ELEMENT,
}
}
Inspect the compact implementation that defines DOM_TYPES, removes null children, maps text nodes, and returns an element virtual node. section 3.5
