Last active
August 29, 2015 14:26
-
-
Save nmn/d369418e61341f207bd4 to your computer and use it in GitHub Desktop.
Quick and dirty hack to make pure functions work in React:
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 component(fn){ | |
class C extends React.Component { | |
render(){ | |
return fn(this.props, this.context) | |
} | |
} | |
C.displayName = fn.displayName || fn.name | |
C.propTypes = fn.propTypes | |
C.contextTypes = fn.contextTypes | |
return C | |
} | |
var pure = new WeakMap() | |
React.oldCreateElement = React.createElement | |
React.createElement = function(tag, props, ...children){ | |
var realTag = tag | |
if(typeof tag === 'function' && !tag.render && !tag.prototype.render){ | |
if(!pure.has(tag)) | |
pure.set(tag, component(tag)) | |
realTag = pure.get(tag) | |
} | |
return React.oldCreateElement(realTag, props, ...children) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your pure functions will have this simple signature:
Further, it supports displayName, propTypes and contextTypes:
It DOES NOT support state. That is a feature.