Skip to content

Instantly share code, notes, and snippets.

@jamesthomasonjr
Last active December 11, 2019 16:30
Show Gist options
  • Save jamesthomasonjr/845c6a62a52af1bcb635eca7b982b2f4 to your computer and use it in GitHub Desktop.
Save jamesthomasonjr/845c6a62a52af1bcb635eca7b982b2f4 to your computer and use it in GitHub Desktop.
Create vanilla DOM objects from JSX
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