reactjshigh-order-component

Is there a away to pass lifecycle hook as a param to a HOC in React?


I'm trying to create a wrapper HOC where I could select which lifecycle hook to pass. I have tried the following HOC:

const HOC = lifeCycleHook => WrappedComponent => {
  return class OriginalComponent extends React.Component {
    lifeCycleHook
    render(){
      return (
        <WrappedComponent {...this.props} />
      );
    }
  }
}

export default HOC;

The component to wrap the original component with:

import React from 'react';
import HOC from './helpers/hoc';
import componentDidMount from './helpers/componentDidMount';

const Home = () => <h1>Home</h1>;

export default HOC(componentDidMount)(Home);

and finally the lifecycle Hook:

import React from 'react';

function componentDidMount(){
  console.log('Test')
}

export default componentDidMount;

EDIT: No compilation errors are thrown, but the console log doesn't fire to print the 'Test'


Solution

  • The recompose package can do this for you. Here's the example from the lifecycle helper:

    const PostsList = ({ posts }) => (
      <ul>{posts.map(p => <li>{p.title}</li>)}</ul>
    )
    
    const PostsListWithData = lifecycle({
      componentDidMount() {
        fetchPosts().then(posts => {
          this.setState({ posts });
        })
      }
    })(PostsList);