Skip to content

Instantly share code, notes, and snippets.

@lmuntaner
Last active May 7, 2023 16:30
Show Gist options
  • Save lmuntaner/629d1c31134bfc7b872683d1be0ff74b to your computer and use it in GitHub Desktop.
Save lmuntaner/629d1c31134bfc7b872683d1be0ff74b to your computer and use it in GitHub Desktop.
Building a React-Like Library
<html>
<body>
<div id="root"></div>
<!-- First article on building a react-like library -->
<script src="./static-dom.js"></script>
<body>
</html>
// Building a React-Like Library: Static Virtual DOM
const render = (vnode, parent) => {
// manage string type
if (typeof vnode === "string") {
return parent.appendChild(document.createTextNode(vnode));
}
// create HTML element
const element = document.createElement(vnode.tag);
// set attributes
if (vnode.props) {
Object.keys(vnode.props).forEach(key => {
const value = vnode.props[key];
element.setAttribute(key, value);
});
}
// iterate over children and render them
if (vnode.children) {
vnode.children.forEach(child => render(child, element));
}
// append the element created
return parent.appendChild(element);
};
const vDom = {
tag: "div",
props: {},
children: [
{
tag: "h1",
props: { id: "title" },
children: ["Hello, World!"]
},
{
tag: "p",
props: {},
children: ["I'm learning about virtual DOM"]
}
]
};
render(vDom, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment