Tracking code for a single-page application made in React


#1

Hope anyone can help me over here to also make this clear for everyone looking for the same kind of information.

After some research I could not find a definitive answer about manually tracking page views in a single-page application without reloading the tracking code.

I found this “Tracking Code Overview”: Tracking Code Overview

There you can see a way to track this kind of apps:

var _hsq = window._hsq = window._hsq || [];
_hsq.push([‘setPath’, ‘/home’]);

var _hsq = window._hsq = window._hsq || [];
_hsq.push([‘setPath’, ‘/about-us’]);
_hsq.push([‘trackPageView’]);

Is this the right way to do it?

Let’s say I have a Single Page App with 3 different URLs: “/”, “/About Us” and “/Contact”.

How would you implement this?

Thanks in advance for any feedback.


#2

Hi @DanielV11,

The _hsq.push([‘setPath’, ‘/about-us’]); and _hsq.push([‘trackPageView’]); lines included in the example are intended to be run when the user changes from the /home page to the /about-us page. This allows you to track new page views without running the tracking code again. In your case, when a user navigates to the /Contact page, you’d run the following:
_hsq.push([‘setPath’, ‘/Contact’]);
_hsq.push([‘trackPageView’]);


#3

If anyone else stumbles across this page while integrating Hubspot with their React App, I built a page listener component that seems to work OK for me. I'm using React Router and Redux:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

var _hsq = window._hsq = window._hsq || [];

class AnalyticsListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.sendPageView(this.context.router.history.location);
    this.context.router.history.listen(this.sendPageView);
  }

  sendPageView(location) {
    _hsq.push(['setPath', location.pathname]);
    _hsq.push(['trackPageView']);
  }

  render() {
    return this.props.children;
  }
}

export default AnalyticsListener

If you're using google analytics, it will play nicely with that as well. This is what my App.js looks like:

const App = () =>
  <Provider store={store}>
    <Router history={history}>
      <AnalyticsListener>
        <Application />
      </AnalyticsListener>
    </Router>
  </Provider>

If Hubspot ever built a custom package for React apps (there are more of us than you think!) then this would be an awesome wrapper element to include.