Skip to content

Instantly share code, notes, and snippets.

@clarabstract
Last active December 2, 2016 03:32
Show Gist options
  • Select an option

  • Save clarabstract/00b4f1d4629ed9b7d0bb75246ef87e94 to your computer and use it in GitHub Desktop.

Select an option

Save clarabstract/00b4f1d4629ed9b7d0bb75246ef87e94 to your computer and use it in GitHub Desktop.
Exposing life-cycle methods as props via a Higher Order Component
// example use
export default let ConnectedActivityFeed = compose(
connect(
({activityFeeds = {}}, {userId}) => ({
feedItems: activityFeeds[userId]
}),
{
onPropsChange: ({userId}) =>
requestActvityFeedData(userId)
}
),
ExposeLifecycle
)(ActivityFeed);
export default function ExposeLifecycle (WrappedComponent) {
class ExposeLifecycleWrapComponent extends Component {
componentWillReceiveProps (nextProps) {
if ( this.props.onComponentWillRecieveProps ) {
this.props.onComponentWillRecieveProps(nextProps);
}
if ( this.props.onPropsChange ) {
this.props.onPropsChange(nextProps);
}
}
componentWillMount () {
if ( this.props.onComponentWillMount ) {
this.props.onComponentWillMount(this.props);
}
if ( this.props.onPropsChange ) {
this.props.onPropsChange(this.props);
}
}
componentWillUnmount () {
if (this.props.onComponentWillUnmount) {
this.props.onComponentWillUnmount(this.props);
}
if ( this.props.onPropsChange ) {
// similar to ref prop behavior
this.props.onPropsChange(null);
}
}
render () {
let {
children,
/* eslint-disable no-unused-vars */
onComponentWillMount,
onComponentWillRecieveProps,
onComponentWillUnmount,
onPropsChange,
/* eslint-enable no-unused-vars */
...props
} = this.props;
if (children) {
return <WrappedComponent {...props}>{children}</WrappedComponent>;
} else {
return <WrappedComponent {...props} />;
}
}
}
mergeStaticOptions(ExposeLifecycleWrapComponent, {
propTypes: WrappedComponent.propTypes,
defaultProps: WrappedComponent.defaultProps,
});
mergeStaticOptions(ExposeLifecycleWrapComponent, {
propTypes: {
onComponentWillMount: PropTypes.func,
onComponentWillRecieveProps: PropTypes.func,
onComponentWillUnmount: PropTypes.func,
onPropsChange: PropTypes.func,
},
});
ExposeLifecycleWrapComponent.displayName = `ExposeLifecycle(${WrappedComponent.displayName || WrappedComponent.name || 'WrappedComponent'})`;
return ExposeLifecycleWrapComponent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment