liveBook · Manning

hString

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

A book-specific JavaScript function that creates a text virtual node from text content.

hString() creates a text virtual node from a string, making common text content easier to place inside a virtual DOM tree. section 3.5.2 section 3.6

Its small implementation has two responsibilities:

  • Represent the node with type set to DOM_TYPES.TEXT. section 3.6
  • Store the supplied string in the value property. section 3.6
  • Let mapTextNodes() convert string children automatically, so callers can write plain strings instead of calling hString() explicitly. section 3.5.2

Direct and automatic text nodes

Both forms describe the same text children: h('div', {}, [hString('Hello '), hString('world!')]) and h('div', {}, ['Hello ', 'world!']). The second form relies on mapTextNodes(). section 3.5.2

export function hString(str) {
  return { type: DOM_TYPES.TEXT, value: str }
}

Use the implementation to see the complete text-node conversion: the function returns an object containing the virtual-node type and string value. section 3.6

function mapTextNodes(children) {
  return children.map((child) =>
    typeof child === 'string' ? hString(child) : child
  )
}

Inspect the companion mapping function that preserves existing virtual nodes while converting string children through hString(). section 3.5.2

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

How deep it goes
Defines the returned object and its automatic string-child mapping, without pursuing production-level DOM optimization.
Examples
Uses Hello-world text children, login-form markup, and counter markup to demonstrate text within virtual DOM trees.
What it assumes
Assumes basic JavaScript functions and objects while teaching text nodes and virtual-node representation directly.
What you can do after
Build it from scratch by returning a text virtual-node object with DOM_TYPES.TEXT and the supplied value.
How it connects
Connects text nodes with virtual DOM, element nodes, fragment nodes, h(), and component views.

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.