liveBook · Manning

createComponentNode

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

A book-specific function that creates and mounts a component from a component virtual node.

createComponentNode mounts a component virtual node by instantiating its component class, passing props, mounting the instance, and preserving runtime references. section 11.1.2

The function performs five focused steps:

  • Reads the component class from vdom.tag and props from vdom.props. section 11.1.2
  • Creates the component instance with new Component(props). section 11.1.2
  • Calls component.mount(parentEl, index) to render and mount its view. section 11.1.2
  • Stores the instance in vdom.component so state survives later DOM patching. section 11.1.2
  • Stores component.firstElement in vdom.el for access to the mounted DOM element. section 11.1.2

Mounting Greetings

A Greetings virtual node can pass { name: 'Jenny' } into the component constructor. The instance mounts its rendered paragraph, then remains attached to the virtual node. section 11.1.2

Listing 11.3 Mounting component virtual nodes (mount-dom.js)
export function mountDOM(vdom, parentEl, index, hostComponent = null) {
  switch (vdom.type) {
    case DOM_TYPES.TEXT: {
      createTextNode(vdom, parentEl, index)
      break
    }

    case DOM_TYPES.ELEMENT: {
      createElementNode(vdom, parentEl, index, hostComponent)
      break
    }

    case DOM_TYPES.FRAGMENT: {
      createFragmentNodes(vdom, parentEl, hostComponent)
      break
    }

    case DOM_TYPES.COMPONENT: {                               #1
      createComponentNode(vdom, parentEl, index, hostComponent)     #2
      break
    }

    default: {
      throw new Error(`Can't mount DOM of type: ${vdom.type}`)
    }
  }
}

The component case in mountDOM delegates component virtual nodes to createComponentNode. section 11.1.2

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

How deep it goes
Implements instantiation, mounting, and virtual-node reference storage, without detailing component updates or DOM patching internals.
Examples
Uses a Greetings component with a name prop and a paragraph-rendering view.
What it assumes
Assumes virtual nodes, component classes, props, mount methods, and render methods are already available.
What you can do after
Build it from scratch by adding component dispatch and implementing the five-step mounting function.
How it connects
Connects virtual DOM, component instances, props, rendering, DOM mounting, and DOM patching.

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.