Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Created October 8, 2019 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelbr/1f4c4cb04ff39695f49024b55e3dc04e to your computer and use it in GitHub Desktop.
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
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