Skip to content

Instantly share code, notes, and snippets.

@nmn
Last active August 29, 2015 14:26
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 nmn/d369418e61341f207bd4 to your computer and use it in GitHub Desktop.
Save nmn/d369418e61341f207bd4 to your computer and use it in GitHub Desktop.
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