Last active
May 7, 2023 16:30
-
-
Save lmuntaner/629d1c31134bfc7b872683d1be0ff74b to your computer and use it in GitHub Desktop.
Building a React-Like Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<div id="root"></div> | |
<!-- First article on building a react-like library --> | |
<script src="./static-dom.js"></script> | |
<body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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