Skip to content

Instantly share code, notes, and snippets.

@Dynalon
Created January 7, 2016 21:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Dynalon/a8790a1fa66bfd2c26e1 to your computer and use it in GitHub Desktop.
Save Dynalon/a8790a1fa66bfd2c26e1 to your computer and use it in GitHub Desktop.
Sample JSX to HTMLElement renderer in TypeScript
// Tiny JSX renderer in TypeScript inspired by plain-jxs: https://github.com/callumlocke/plain-jsx
// Babel would allow you to specify the factory function as special inline comment:
/** @jsx JSXrender */
let JSXrender = (tagName: string, attributes?: { [key: string]: any }, ...children: Array<HTMLElement |  string>): HTMLElement => {
if (!tagName || typeof tagName !== 'string')
throw new Error("tagName has to be defined, non-empty string");
attributes = attributes || {};
children = children || [];
let element = document.createElement(tagName);
for (let attribute_key of Object.keys(attributes)) {
let attribute_value = attributes[attribute_key];
element.setAttribute(attribute_key, attribute_value);
}
for (let child of children) {
if (child instanceof HTMLElement)
element.appendChild(child);
else if (typeof child === 'string')
element.appendChild(document.createTextNode(child));
}
return element;
}
// Shim as TS does not yet allow custom factory functions besides React
let React = {
createElement: JSXrender
};
// Test it:
let heading = "Hello world!";
let rendered = <h1>{heading}</h1>
document.body.appendChild(rendered);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment