liveBook · Manning

H function

As explained in Build a Frontend Web Framework (From Scratch)

A framework function that constructs a virtual DOM node representation from an element description and its properties and children.

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

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Defines the function’s inputs, defaults, normalization, and returned shape without pursuing rendering internals or optimization.
Examples
Uses login forms, counter markup, HTML-to-virtual-DOM exercises, and generated placeholder paragraphs.
What it assumes
Starts from familiar HTML elements and JavaScript objects while requiring no manually constructed virtual DOM tree.
What you can do after
Build it from scratch and apply it to declare virtual DOM trees for framework views.
How it connects
Connects virtual DOM, virtual nodes, text nodes, fragments, components, event listeners, hyperscript, JSX, and React.createElement().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.