Skip to content

Instantly share code, notes, and snippets.

@intrnl
Created June 18, 2022 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/e2dd3d82cf47229dc889f171cea2d1cb to your computer and use it in GitHub Desktop.
Save intrnl/e2dd3d82cf47229dc889f171cea2d1cb to your computer and use it in GitHub Desktop.
JSX to DOM nodes
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