Q15: Write a Simple Virtual DOM Render Function
Implement a render(vnode) function that converts Virtual DOM element objects ({ type, props, children }) or text primitives into real DOM Node instances.
VNode to Real DOM Compiler
function render(vnode) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return document.createTextNode(String(vnode));
}
const el = document.createElement(vnode.type);
if (vnode.props) {
Object.entries(vnode.props).forEach(([key, val]) => {
if (key.startsWith('on')) {
el.addEventListener(key.slice(2).toLowerCase(), val);
} else {
el.setAttribute(key, val);
}
});
}
if (vnode.children) {
vnode.children.forEach(child => el.appendChild(render(child)));
}
return el;
}💡 Recursively converts element descriptors into real DOM nodes, registering event listeners for 'on' props.
Key Takeaways
- Recursively processes tree node structures using DOM API creation calls.
- Distinguishes text nodes, attribute props, and on event listener bindings.
Knowledge Check
How does the render function handle event props like onClick: fn?