-
-
Save rglover/854830b63c995176ca4cc96f39560c65 to your computer and use it in GitHub Desktop.
Sample JSX to HTMLElement renderer in TypeScript
This file contains hidden or 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
// 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