Skip to content

Instantly share code, notes, and snippets.

@lusentis
Last active March 14, 2016 10:49
Show Gist options
  • Save lusentis/910573ef818ca1c2e8e0 to your computer and use it in GitHub Desktop.
Save lusentis/910573ef818ca1c2e8e0 to your computer and use it in GitHub Desktop.
add lifecycle methods to functional components
import addLifecycle from './addLifecycle';

const wrapLifecycle = addLifecycle({
  handleComponentDidMount: triggerRequestFetch,
  handleComponentWillReceiveProps: Function,
});

// ...

export default connectRedux(wrapLifecycle(PostEditor));
/* eslint react/no-multi-comp:[0], react/display-name:[0] */
import React, { PropTypes as Type } from 'react';
class LifecycleComponent extends React.Component {
componentDidMount() {
this::this.props.handleComponentDidMount();
}
componentWillReceiveProps() {
this::this.props.handleComponentWillReceiveProps();
}
shouldComponentUpdate(nextProps) {
return this.props !== nextProps; // immutable!
}
render() {
const { children } = this.props;
return React.cloneElement(children, this.props);
}
}
LifecycleComponent.propTypes = {
children: Type.element.isRequired,
handleComponentDidMount: Type.func.isRequired,
handleComponentWillReceiveProps: Type.func.isRequired,
};
const wrapper = ({
handleComponentDidMount,
handleComponentWillReceiveProps,
}) => Child => props => (
<LifecycleComponent
handleComponentDidMount={handleComponentDidMount}
handleComponentWillReceiveProps={handleComponentWillReceiveProps}
{...props}
>
<Child {...props} />
</LifecycleComponent>
);
export default wrapper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment