Skip to content

Instantly share code, notes, and snippets.

@nmn
Last active Aug 29, 2015
Embed
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 {
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)
}
@nmn
Copy link
Author

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