Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating a React SPA with hotjar heatmap tracking

I am trying to integrate the Hotjar library to track heatmaps for users in our React SPA.

I have followed the general tutorials but I have not been able to get this working.

I have the standard Hotjar tracking code in the element of the document.

I am using a Higher Order Component to hook into React router and have attempted to call both window.hj('stateChange', page) and window.hj('vpv', page) but none of this has been logged in Hotjar heatmaps.

Here is the code for the HOC:

import React, { Component } from 'react';
import GoogleAnalytics from 'react-ga';

GoogleAnalytics.initialize(process.env.REACT_APP_GA_TRACKING_ID);

const withPageViewTracker = (WrappedComponent, options = {}) => {
  const trackPage = page => {
    console.log('window.hj', window.hj);
    console.log('page', page);
    // window.hj('stateChange', page);
    window.hj('vpv', page);
  };

  const HOC = class extends Component {
    componentDidMount() {
      const page = this.props.location.pathname;
      trackPage(page);
    }

    componentWillReceiveProps(nextProps) {
      const currentPage = this.props.location.pathname;
      const nextPage = nextProps.location.pathname;

      if (currentPage !== nextPage) {
        trackPage(nextPage);
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };

  return HOC;
};

export default withPageViewTracker;

Here is how I use the HOC:

<Route exact path="/" component={withPageViewTracker(Welcome)} />
like image 724
daveGeo Avatar asked Sep 29 '17 07:09

daveGeo


2 Answers

You can use react hotjar
https://www.npmjs.com/package/react-hotjar

You can inject the hotjar where ever you want within the component

Make sure to use it after the component is mounted

componentDidMount() {
    hotjar.initialize('xxxxxxx', x);
  }

If you are using hooks you can do in useEffect with out any dependency array

const SampleComponent = () => {
  useEffect(() => {
    hotjar.initialize('xxxxxxx', x);
  }, [])

Make sure to load hotjar after all async stuffs are done , so it will record all activities you want

async componentDidMount() {
        await load1();
        await load2();
        hotjar.initialize('xxxxxxx', x);
}
like image 171
sumit Avatar answered Sep 17 '22 14:09

sumit


By default Hotjar works on SPA. And by default they track the changes in url if it's url changes, not hashchange.

If you want Hotjar to track hashchanges then you need to configure that in the settings.

Within Sites & Organizations, you can reach your Site Settings. Here, you can specify how Hotjar should track URL changes if the default settings don't work. Below is an explanation of all the options.

Hotjar Site Settings

like image 39
Ahmed Mahmoud Avatar answered Sep 18 '22 14:09

Ahmed Mahmoud