Created
October 8, 2019 20:05
-
-
Save mikaelbr/6318e90de02302b7644fd735e5111afe to your computer and use it in GitHub Desktop.
Code for blogpost "Using JSX for your own lightweight declarative library": https://medium.com/@mikaelbrevik/using-jsx-for-your-own-lightweight-declarative-library-a773d3796475
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
const isFunction = s => typeof s === "function"; | |
function createElement(tag, props, ...children) { | |
// If first argument is function, we know it is custom component, | |
// So call it as a function, passing the props with children as a property. | |
// Using spread like this will work when props is `null` also | |
if (isFunction(tag)) { | |
return tag({ ...props, children }); | |
} | |
// Same as before | |
const el = attrs(document.createElement(tag), props); | |
children.forEach(child => { | |
const node = !isString(child) ? child : document.createTextNode(child); | |
el.appendChild(node); | |
}); | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment