Created
June 18, 2022 03:12
-
-
Save intrnl/e2dd3d82cf47229dc889f171cea2d1cb to your computer and use it in GitHub Desktop.
JSX to 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
export function h (type, props, ...children) { | |
if (typeof type === 'function') { | |
if (props === null) { | |
props = {}; | |
} | |
if (children.length > 0) { | |
props.children = children; | |
} | |
return type(props); | |
} | |
const node = type === null | |
? document.createDocumentFragment() | |
: document.createElement(type, { is: props && props.is }); | |
if (props && type) { | |
for (let key in props) { | |
const value = props[key]; | |
if (typeof value !== 'function') { | |
if (value != null && (value !== false || key.startsWith('aria-'))) { | |
node.setAttribute(key, value); | |
} | |
else { | |
node.removeAttribute(key); | |
} | |
} | |
} | |
} | |
for (let idx = 0, len = children.length; idx < len; idx++) { | |
const child = children[idx]; | |
if (child == null || child === true || child === false) { | |
// do nothing | |
} | |
else if (Array.isArray(child)) { | |
children = children.slice(0, idx).concat(child, children.slice(idx + 1)); | |
len += child.length - 1; | |
idx--; | |
} | |
else if (child instanceof Node) { | |
node.appendChild(child); | |
} | |
else { | |
node.appendChild(document.createTextNode(child)); | |
} | |
} | |
return node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment