Last active
May 6, 2024 04:58
-
-
Save treshugart/86b229d172045298e6c7 to your computer and use it in GitHub Desktop.
Use JSX with the native DOM.
This file contains hidden or 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 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; | |
} | |
}; |
The shouldBeProp
function allows you to do things like:
<my-element
some-attr="some value"
someProp=<sub-element />
/>
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
Babel compiles things down to
React.createElement()
calls, so all you really have to do is simply transpile your code and include this. If you don't want to dowindow.React
, you can include this as a shim in the transpiled code as a localReact
variable by just changingwindow.React
to beconst React
or something.