Integrating a React SPA with hotjar heatmap tracking
Asked Answered
Y

2

17

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)} />
Yepez answered 29/9, 2017 at 7:49 Comment(4)
What have you tried? Can you share some code?Guy
I've edited my postYepez
Which version of React Router are you using?Guy
@davegeo did you figure this one out?Merat
L
9

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);
}
Lavolta answered 17/1, 2020 at 5:51 Comment(0)
P
4

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

Parkway answered 22/7, 2018 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.