Last active
November 21, 2019 23:04
-
-
Save foxbunny/c38a205587679befa9ae5414c7d95838 to your computer and use it in GitHub Desktop.
JSX helper for creating DOM nodes
This file contains 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
const h = (tag, attrs, ...children) => { | |
const elm = document.createElement(tag) | |
for (let key in attrs) { | |
if (key.slice(0, 2) == 'on') { | |
const evtName = key.slice(2) | |
const cb = attrs[key] | |
if (cb == null) continue // we can use null or undefnied to suppress | |
elm.addEventListener(evtName, cb) | |
} else if (['disabled', 'autocomplete', 'selected', 'checked'].indexOf(key) > -1) { | |
if (attrs[key]) { | |
elm.setAttribute(key, key) | |
} | |
} else { | |
if (attrs[key] == null) continue // Don't set undefined or null attributes | |
elm.setAttribute(key, attrs[key]) | |
} | |
} | |
if (children.length === 0) { | |
return elm | |
} | |
forEach(child => { | |
if (child instanceof Node) { | |
elm.appendChild(child) | |
} else { | |
elm.appendChild(document.createTextNode(child)) | |
} | |
}, flatten(children)) | |
return elm | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment