Our first VDOM function
Now that we understand what the virtual DOM is, we can write our first function:
function createVNode(type, props, children) {return {type,props,children,};}
This function probably seems so simple that it's almost not necessary - all it's doing is turning the function arguments into object properties. This function will change as we continue writing our virtual DOM library, but for now we can just enjoy that it is so simple.
So how do we actually use this function? Let's start with something simple: a VDOM tree that represents a <h1>
element containing the text Hello, World!
.
createVNode("h1", null, ["Hello, World!"]);
Simple! This function call will return a VDOM tree that looks like this:
{"type": "h1","props": null,"children": ["Hello, World!"]}
This VDOM tree represents a real DOM tree that would have the following HTML:
<h1>Hello, World!</h1>
In theory there is no limit to how deep a VDOM tree can be nested. We can create a more complex example that has more nesting, and combines text nodes with other vnodes:
createVNode("div", { className: "container" }, [createVNode("h1", null, ["Hello, World!"]),createVNode("p", null, ["We're building a ",createVNode("small", null, ["(really simple)"])," virtual DOM library.",]),]);
This code will generate a VDOM tree that looks like this:
{"type": "div","props": {"className": "container"},"children": [{"type": "h1","props": null,"children": ["Hello, World!"]},{"type": "p","props": null,"children": ["We're building a ",{"type": "small","props": null,"children": ["(really simple)"]}," virtual DOM library."]}]}
This super-simple implementation of createVNode
is powerful enough to handle everything we need to do for now. It helps us build a virtual representation of a DOM tree where we can control which attributes are on each node and what (if any) child nodes each node has. It's useful to see the virtual DOM objects that our library will be using, but these objects alone are not very useful. In the next section we're going to write the code that mounts these VDOM tree objects into the real DOM.