Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active May 18, 2016 16:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

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 do window.React, you can include this as a shim in the transpiled code as a local React variable by just changing window.React to be const React or something.

@treshugart
Copy link
Author

The shouldBeProp function allows you to do things like:

<my-element
  some-attr="some value"
  someProp=<sub-element /> 
/>

@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