Skip to content

Instantly share code, notes, and snippets.

@trevsm
Created May 17, 2021 21:26
Show Gist options
  • Save trevsm/29dd30c400881647e99f380f67e2f9b5 to your computer and use it in GitHub Desktop.
Save trevsm/29dd30c400881647e99f380f67e2f9b5 to your computer and use it in GitHub Desktop.
React-like createElement for manual jsx
function createElement(tag, attrs, ...children) {
// Custom Components will be functions
if (typeof tag === 'function') { return tag() }
// regular html tags will be strings to create the elements
if (typeof tag === 'string') {
// fragments to append multiple children to the initial node
const fragments = document.createDocumentFragment()
const element = document.createElement(tag)
children.forEach(child => {
if (child instanceof HTMLElement) {
fragments.appendChild(child)
} else if (typeof child === 'string'){
const textnode = document.createTextNode(child)
fragments.appendChild(textnode)
} else {
// later other things could not be HTMLElement not strings
console.log('not appendable', child);
}
})
element.appendChild(fragments)
// Merge element with attributes
Object.assign(element, attrs)
return element
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment