Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active May 6, 2024 04:58
Show Gist options
  • Save treshugart/86b229d172045298e6c7 to your computer and use it in GitHub Desktop.
Save treshugart/86b229d172045298e6c7 to your computer and use it in GitHub Desktop.
Use JSX with the native DOM.
function shouldBeProp (item) {
return typeof item === 'function' || typeof item === 'object';
}
window.React = {
createElement (name, attrs, ...chren) {
const node = typeof name === 'function' ? name() : document.createElement(name);
Object.keys(attrs || []).forEach(attr => shouldBeProp(attrs[attr]) ? node[attr] = attrs[attr] : node.setAttribute(attr, attrs[attr]));
chren.forEach(child => node.appendChild(child instanceof Node ? child : document.createTextNode(child)));
return node;
}
};
@treshugart
Copy link
Author

Added the ability to specify a function as the tag name:

function myElement () {
  return document.createElement('my-element');
}

// Creates <my-element />
<myElement />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment