Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
Quick and dirty hack to make pure functions work in React:
function component(fn){
class C extends React.Component {
return fn(this.props, this.context)
C.displayName = fn.displayName ||
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){
pure.set(tag, component(tag))
realTag = pure.get(tag)
return React.oldCreateElement(realTag, props, ...children)
Copy link

nmn commented Aug 4, 2015

Your pure functions will have this simple signature:

(props, context) => ReactElement

Further, it supports displayName, propTypes and contextTypes:

function MyPureComponent(props, context){...}
MyPureComponent.displayName = 'MyPureComponent'
MyPureComponent.propTypes = {...}
MyPureComponent.contextTypes = {...}

It DOES NOT support state. That is a feature.

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