Skip to content

Instantly share code, notes, and snippets.

@cyrilf
Created January 17, 2018 11:46
Show Gist options
  • Save cyrilf/4c62ea5bf6d89bace84377e4135098a6 to your computer and use it in GitHub Desktop.
Save cyrilf/4c62ea5bf6d89bace84377e4135098a6 to your computer and use it in GitHub Desktop.
React custom life-cycle method
// 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