Last active
August 29, 2024 10:54
-
-
Save erdesigns-eu/b54c872e034798b648a260af0fec1a6b to your computer and use it in GitHub Desktop.
JSX DOM
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
type Attrs = { | |
[key: string]: any; | |
}; | |
const h = (tag: string, attrs: Attrs, ...children: (Node | string)[]): HTMLElement => { | |
const elm = document.createElement(tag); | |
for (let key in attrs) { | |
if (key.startsWith('on')) { | |
const evtName = key.slice(2); | |
const cb = attrs[key]; | |
if (cb === null) { | |
continue; | |
} | |
elm.addEventListener(evtName, cb); | |
} | |
else if (['disabled', 'autocomplete', 'selected', 'checked'].includes(key)) { | |
if (attrs[key]) { | |
elm.setAttribute(key, key); | |
} | |
} | |
else { | |
if (attrs[key] === null) { | |
continue; | |
} | |
elm.setAttribute(key, attrs[key]); | |
} | |
} | |
if (children.length > 0) { | |
children.flat().forEach((child) => { | |
if (child instanceof Node) { | |
elm.appendChild(child); | |
} | |
else { | |
elm.appendChild(document.createTextNode(child)); | |
} | |
}); | |
} | |
return elm; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: