Last active
August 16, 2021 23:17
-
-
Save tarcisiozf/a87cdf4866590567258e22dfddad690c to your computer and use it in GitHub Desktop.
easier dom components in js (without jsx), inspired by h
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 { ul, li } = require('./html') | |
const list = ul({ title: 'awesome list' }, | |
li({ title: 'interactive', onclick: () => alert(1) }, 'first'), | |
li('second') | |
) | |
document.body.appendChild(list) |
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 textContent = (el, content) => { | |
el.textContent = content | |
} | |
const children = (el, children) => { | |
children.forEach(child => el.appendChild(child)) | |
} | |
const attributes = (el, attributes) => { | |
Object.entries(attributes).forEach(([key, value]) => { | |
if (typeof value === 'function') { | |
el[key] = value | |
} else { | |
el.setAttribute(key, value) | |
} | |
}) | |
} | |
const tag = function (name) { | |
return (head, ...tail) => { | |
const type = typeof head | |
const element = document.createElement(name) | |
// el(content: string) | |
if (type === 'string') { | |
textContent(element, head) | |
} | |
// el(children: array) | |
else if (Array.isArray(head)) { | |
children(element, head) | |
} | |
// el(attributes: object, content: string | array) | |
else if (type === 'object' && head !== null) { | |
const firstChild = tail[0] | |
if (typeof firstChild === 'string') { | |
textContent(element, firstChild) | |
} | |
else { | |
children(element, tail) | |
} | |
attributes(element, head) | |
} | |
else { | |
throw new Error() | |
} | |
return element | |
} | |
} | |
module.exports = new Proxy({}, { | |
get: function (target, prop) { | |
return tag(prop) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment