Created
January 17, 2018 11:46
-
-
Save cyrilf/4c62ea5bf6d89bace84377e4135098a6 to your computer and use it in GitHub Desktop.
React custom life-cycle method
This file contains 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
// Inspired by https://github.com/MicheleBertoli/react-automata/blob/d9128bebe30df83c41bff4ed806549241fcf3b04/src/withStatechart.js | |
// Example of how to use a custom life-cycle method for a wrapped component | |
import React from 'react' | |
const isStateless = Component => | |
!(Component.prototype && Component.prototype.isReactComponent) | |
const withSomething = Component => { | |
class ComponentWrapper extends React.Component { | |
constructor(props) { | |
super(props) | |
this.handleRef = isStateless(Component) ? null : this.handleRef | |
} | |
handleRef = element => { | |
this.instance = element | |
} | |
handleTransition = (event) => { | |
if (this.instance && this.instance.componentWillTransition) { | |
this.instance.componentWillTransition(event) | |
} | |
// do some other stuff | |
// ... | |
} | |
render() { | |
return ( | |
<Component | |
{...this.props} | |
ref={this.handleRef} | |
transition={this.handleTransition} | |
/> | |
) | |
} | |
} | |
return ComponentWrapper | |
} | |
export default withSomething |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment