简体   繁体   中英

How to write a recompose HOC to User Analytics?

I'm currently sending user analytic tracking events without a HOC like so:

import React from 'react';

class NamePage extends Component {

  componentDidMount() {
    this.context.mixpanel.track('View Page: NamePage');
  }
  render() {
  ...
  }
}

NamePage.contextTypes = {
    mixpanel: PropTypes.object.isRequired
};

export default NamePage;

Given 99% of my pages will require this track function, I'm learning that, I should wrap my pages in a recompose HOC.

Can do something like:

import React from 'react';
import withTracking from '../hoc/withTracking';

class NamePage extends Component {

  render() {
  ...
  }
}
export default withTracking(NamePage, {
  eventTitle: 'View Page: NamePage',
});

Is this possible? Am I setting this up correctly? Is there a better way to add a HOC for this purpose?

Thank you

Take a look at lifecycle method . It takes object with all lifecycle methods you want and returns a HOC that will add methods to the component.

I suggest you to change withTracking API slightly. You can make it composable by making withTracking a factory function with eventTitle argument.

 import React from 'react';
 import {lifecycle, compose} from recompose;

 export function withTracking(eventTitle) {
     return lifecycle({
         componentDidMount() {
             this.context.mixpanel.track(eventTitle);
         }
     });
 }

 const class NamePage extends Component {
     render(){
         ...
     }
 }

 export default withTracking('View Page: NamePage')(NamePage);

 // and now you can compose withTracking with some other HOCs if needed
 // for example:

 export default compose(
     withTracking('View Page: NamePage'),
     someAnotherHOC,
     someAnotherHOC2
 )(NamePage)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM