A component virtual node lets a virtual DOM tree contain stateful components alongside elements, text, and fragments. Its type is component, its tag is the component prototype, and its props carry data from the parent. section 11.1
Build the mechanism around three responsibilities:
- Create the node with h(): classify a string tag as an element and a non-string tag as a component, then retain tag, props, and children. section 11.1
- Mount the node by instantiating vdom.tag with vdom.props, mounting the component, and saving both the component instance and its first DOM element. section 11.1.2
- Patch the node by reusing the old instance, passing it the new props, and saving that instance and its current first element on the new virtual node. section 11.1.4
- Compare component nodes by type and component prototype, using equality of their tag values to decide whether they represent the same component. section 12.1.1
A component in a parent tree
Calling h(FooComponent) can produce a component node such as { type: 'component', tag: FooComponent, props: {}, children: [] }. During mounting, new FooComponent(props) creates the instance; during patching, the saved instance receives updated props instead of being recreated. section 11.1 section 11.1.2 section 11.1.4
Listing 11.4 Mounting a component node (mount-dom.js)
function createComponentNode(vdom, parentEl, index, hostComponent) {
const Component = vdom.tag #1
const props = vdom.props #2
const component = new Component(props) #3
component.mount(parentEl, index) #4
vdom.component = component #5
vdom.el = component.firstElement #6
}
Inspect the small mounting function that connects the virtual node’s prototype and props to a live component instance, then records the instance and first element. section 11.1.2
Listing 11.8 Patching a component node (patch-dom.js)
function patchComponent(oldVdom, newVdom) {
const { component } = oldVdom #1
const { props } = newVdom #2
component.updateProps(props) #3
newVdom.component = component #4
newVdom.el = component.firstElement #5
}
Inspect the patching function that updates the existing component instance and transfers its references to the new virtual node. section 11.1.4
