Integrating Hotjar for Heatmap Tracking in a React SPA

To successfully track user interactions in your React Single Page Application (SPA) using Hotjar, you need to implement the Hotjar tracking code and ensure that page views are logged correctly. This guide will walk you through the necessary steps.

Step 1: Add Hotjar Tracking Code

First, ensure that you have included the standard Hotjar tracking code in the <head> section of your HTML document. This is essential for Hotjar to function properly.

Step 2: Create a Higher Order Component (HOC)

To track page views effectively, you can create a Higher Order Component (HOC) that hooks into the React Router. This HOC will call the appropriate Hotjar functions whenever the route changes. Below is an example implementation:

import React, { Component } from 'react';

const withHotjarTracking = (WrappedComponent) => {
  const trackPageView = (page) => {
    console.log('Tracking page view:', page);
    // Use Hotjar's vpv function to log the virtual page view
    window.hj('vpv', page);
  };

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

    componentDidUpdate(prevProps) {
      const currentPage = this.props.location.pathname;
      const previousPage = prevProps.location.pathname;

      if (currentPage !== previousPage) {
        trackPageView(currentPage);
      }
    }

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

  return HOC;
};

export default withHotjarTracking;

Step 3: Use the HOC with Your Routes

You can now use the withHotjarTracking HOC to wrap your components in your routing configuration. For example:

<Route exact path="/" component={withHotjarTracking(Welcome)} />

Conclusion

By following these steps, you can effectively integrate Hotjar into your React SPA to track user interactions through heatmaps. Make sure to test the implementation to confirm that page views are being logged correctly in your Hotjar account.