Using JSX in Typescript without React

JSX became a defacto standard for mixing in XML markup in JS or TypeScript source files. With a little trick it can be used for quickly creating DOM elements or for templating.

The following snippet can be dropped into a JSX file and will then make a HTMLElement of the XML markup:

var React = {
    createElement: function (tag, attrs, children) {
        var e = document.createElement(tag);

        // Add attributes
        for (var name in attrs) {
            if (name && attrs.hasOwnProperty(name)) {
                var v = attrs[name];
                if (v === true) {
                    e.setAttribute(name, name);
                } else if (v !== false && v != null) {
                    e.setAttribute(name, v.toString());
                }
            }
        }

        // Append children
        for (var i = 2; i < arguments.length; i++) {
            var child = arguments[i];
            e.appendChild(
                child.nodeType == null ?
                doc.createTextNode(child.toString()) :
                child);
        }

        return e;
    }
}

The same approach could be used to directly generate a HTML string for templating.

It is then easy to do something like:

document.querySelector('#menu').appendChild(
    <li class={active ? 'active' : false}>
        {title}
    </li>
);

Published on August 11, 2016

 
Back to posts listing