Search code examples
javascriptangularjsreactjsgoogle-analyticsvirtual-dom

Tracking a ReactJS application


I have been working with AngularJS and its structure is in a way that, as the user browses around the website, only views and routes change and there are no pageviews and etc triggered (GTM is not loaded per route).

Hence, I have faced quite a number of issues in Google analytics (even Angulartics is not too promising), when working with AngularJS websites.

Now I am reading on ReactJS, and I am very keen to use it along with Laravel. I am only concerned that the entire virtual DOM concept of React, would indeed create a similar tracking pain afterwards, as it would mean that the Google Tag Manager container might not be loaded every time a user lands on a page.

Anybody facing issues tracking React applications?


Solution

  • You mount React to a given DOM element, which then becomes a mount root element. Only these elements will be changed, meaning that if you have script tags and alike, not inside react, these will not be affected

    <html>
      <head>
        <script src="/gtm.js"></script>
        <script src="/react.js"></script>
      </head>
      <body>
        <div id="mount">
        </div>
        <script>
          class Test extends React.Component {
            track() {
              window.dataLayer.push({
                event: 'Stuff'
              });
            }
    
            render() {
              return <button onClick={this.track} />;
            }
          }
          React.render(<Test />, document.getElementById('mount'))
        </script>
    </html>
    

    In that React can only modify in content inside #mount, and therefore the gtm tag should always be present.