Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.