5

I am using Google Tag Manager to push pageview events to the datalayer for Analytics tracking. This is happening in componentDidMount() (and sometimes componentWillReceiveProps() if I am listening for query string parameter changes with the location prop using withRouter).

I am using react-helmet to dynamically update my title and other tags as components change.

I have noticed an issue that I am getting the improper page title in Analytics. It's frequently showing the page title of the previous page, instead of the one I am currently on. It appears that react-helmet is not updating the tag until after componentDidMount().

Page View Event Function Example

My analytics tag in GTM is called every time this event is pushed to the data layer

const firePageViewEvent = () => {
      console.log("Pageview event fired (from tracking script)");

      if (window && window.dataLayer) {
          console.log("window and dataLayer exist, pushing pageview event.");
          let dataLayer = window.dataLayer || [];
          dataLayer.push({
              'event': 'reactPageViewEvent'
          });
      } else {
          console.log("window or dataLater does not exist, cannot push pageview event.");
      }
};
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61

1 Answers1

2

I can confirm that wrapping the function in a setTimeOut() function with a 0ms delay does indeed work to ensure that the event is only pushed after react-helmet has a chance to do its thing.

This allows me to consistently get the current page title in Analytics.

See github issue comment

Updated Function

const firePageViewEvent = () => {
    setTimeout(() => {
        console.log("Pageview event fired (from tracking script)");

        if (window && window.dataLayer) {
            console.log("window and dataLayer exist, pushing pageview event.");
            let dataLayer = window.dataLayer || [];
            dataLayer.push({
                'event': 'reactPageViewEvent'
            });
        } else {
            console.log("window or dataLater does not exist, cannot push pageview event.");
        }
    }, 0);
};
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
  • There may be a better solution now, but over a year ago this was the only workaround to be found. – Matthew Rideout Aug 28 '19 at 01:57
  • that issue is still there ... https://github.com/nfl/react-helmet/issues/189 ! Let's have a dataLayer.push({'event':'pageTitleUpdated'} occur when it is done Or push values to be used by GA when available and configure GA to use these instead of the defaults DOM values – Open SEO Apr 19 '20 at 09:27
  • 1
    10x Matthew, these React / GTAGs and Helmets are driving me crazy!!! – Valentin Petkov May 25 '21 at 11:54