Created
May 17, 2021 21:26
-
-
Save trevsm/29dd30c400881647e99f380f67e2f9b5 to your computer and use it in GitHub Desktop.
React-like createElement for manual jsx
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
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