Created
October 8, 2019 19:57
-
-
Save mikaelbr/1f4c4cb04ff39695f49024b55e3dc04e 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 isString = s => typeof s === "string"; | |
function createElement(tag, props, ...children) { | |
const el = document.createElement(tag); | |
// Iterate thorugh all rest arguments as children. | |
children.forEach(child => { | |
// If string, we make it a text node. | |
const node = !isString(child) ? child : document.createTextNode(child); | |
// Add the child to the newly created elements. | |
el.appendChild(node); | |
}); | |
return el; | |
} | |
const h1 = <h1>Hello, World</h1>; | |
// Output HTML | |
//> <h1>Hello, World</h1> | |
const list = ( | |
<ul> | |
<li>Peter</li> | |
<li>Paul</li> | |
<li>Mary</li> | |
</ul> | |
); | |
// Output HTML | |
//> <ul><li>Peter</li><li>Paul</li><li>Mary</li></ul> | |
// Example usage | |
document.body.appendChild(list); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment