Last active
December 11, 2019 16:30
-
-
Save jamesthomasonjr/845c6a62a52af1bcb635eca7b982b2f4 to your computer and use it in GitHub Desktop.
Create vanilla DOM objects from 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 element(type, newProps, ...children) { | |
const element = document.createElement(type); | |
if (newProps) { | |
Object.entries(newProps).forEach(([key, value]) => { | |
if (typeof value == 'function') { | |
element[key] = value; | |
} else { | |
element.setAttribute(key, value); | |
} | |
}); | |
} | |
if (children) { | |
children.forEach(child => element.append(child)); | |
} | |
return element; | |
} | |
function fragment(...children) { | |
const fragment = document.createDocumentFragment(); | |
if (children) { | |
children.forEach(child => fragment.append(child)); | |
} | |
return fragment; | |
} | |
export default function jsx(type, newProps, ...children) { | |
if (type === 'fragment') { | |
return fragment(...children); | |
} | |
return element(type, newProps, ...children); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment