Home > References > SEO

React js google tag manager: React Google analytics problem solved

Last updated : 6 April 2021

Google tag manager, out of the box is unable to track React js page navigations using react-router. The reason is because of how the react-router uses react virtual dom to manipulate the view. Unlike traditional anchor tags, React's router Link doesn't do a full page reload. Instead, the router Link only updates the altered dom elements and leaves the rest of the dom untouched. That is the expected behavior and much more efficient than whole dom manipulation.

This article explains how the React js Router works and how to make Google tag manager work with React js. If you are in a hurry to make analytics work with React js and are not interested in the reasons, jump to the Google tag manager solution for React js.

React js is a JavaScript library for building user interface components. React js uses the virtual dom concept to update the view efficiently compared to traditional dom-manipulation technics. React updates only the necessary parts of the dom, leaving the rest of the dom unchanged. Therefore, clicking on a react <Link/> and a traditional <a href/> behave differently.

React js Link is derived from react-router-dom. Therefore, react Link is used to routing through virtual dom instead of real dom. Any changes detected during the transition are updated to the real dom. For example, the illustration below represents a page transition from page 1 to page 2 in react js. Note that the only change between the two pages is the content image. The rest of the page remains the same. React detects this change by comparing the virtual dom and re-renders only the changed portion of the dom. In this case, the content component.

React virtual DOM
Figure 1 : React virtual DOM

Using the traditional anchor tag in place of the react Link would result in the entire page load regardless most of the page content remains the same.

The main advantage of the react Link is performance due to efficient dom manipulation. As I mentioned earlier, the changes are compared in the virtual dom and update only necessary elements in the real dom, avoiding a total dom re-render.

One potential drawback is external javascript execution. The javascript files you import in your application and javascript code reside inside the page header or body is executed only once. That's when you enter the page by typing the URL or any way that causes a full page load. And this is also the reason why Google analytics does not track your internal page navigations.

Google tag manager solution for React js

So how can I make the tag manager work with React js applications? The answer lies in the Google tag manager console. The tag manager's History Change trigger can track all the client-side navigations using React router links. But you still need to insert the tag manager scripts somewhere in your application. Another option is to use the react-gtm-module package from npm. Both methods are discussed below. If you have already inserted tracking scripts, you can skip to the section to create the history change trigger in Google tag manager.

Method 1: Using tag manager scripts

Where to insert tag manager scripts?

It has to be a page common to all the pages of your application. index.html is the best candidate that comes to my mind. Note: If you use this method, do not use method 2. Go to Creating history change trigger in the Google tag manager console section.

<!DOCTYPE html>
<html lang="en">
	<!-- Google Tag Manager - as high in the <head> of the page -->
	  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
	<!-- End Google Tag Manager -->
    <title>React App</title>
    <!--immediately after the opening <body> tag-->
	  <noscript><frame src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
	  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
	<!-- End Google Tag Manager (noscript) -->
    <div id="root"></div>

Method 2: Using react-gtm-module

How to use react-gtm-module?

To include the react-gtm-module, use
npm install react-gtm-module --save
edit your package.json file and add "react-gtm-module": "^2.0.11" as a dependency.

Now we have to place the tracking code in the application. The same rule applies to the tag manager scripts, but we cannot select the index.html this time. The below example uses App.js, but your choices may vary depending on your app architecture.

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import TagManager from 'react-gtm-module';
import Users from './Users'
import Posts from './Posts'
import Login from './Login';
const App = () => {
  useEffect(() => {
	TagManager.initialize({ gtmId: 'GTM-XXXXX' });
  }, []);
  return (
          <Route path="/" component={Users} exact />
          <Route path="/posts" component={Posts} exact />
          <Route path="/login" component={Login} exact />
export default App;

Creating history change trigger in the Google tag manager console

Now it's time to create a history change trigger in the Google tag manager console. Log into google tag manager and follow the below steps.

  • Select workspace and click Triggers
Google tag manager triggers
Figure 2 : Adding a trigger on Google tag manager
  • To create a new trigger, click New -> Trigger Configuration and select History Change trigger from the list.
History Change trigger
Figure 3 : Trigger Configuration Select History Change trigger
  • Make sure to check All History Changes.
Saving History Change trigger
Figure 4 : Give a name and save the trigger
  • Name the trigger and click save.

Don't forget to publish your workspace container. Now you would see a history change trigger for navigations happen within your application.

Debug google tag manager with tag assistant

We can use Google tag assistant to ensure all the intended triggers are triggered on your page navigations. To start a debug session, click the Preview button on the top right. Once you click start, the tag manager will open a debug window connected to your website. If it fails to connect the debugger to your website, close the tab and restart the debug session. I have experienced this issue several times. Once the session is successful, use the window to navigate your website links. You will notice the history trigger fires on each navigation.

Google tag manager debugger
Figure 5 : Srart a debug session by clicking the Preview button on the top right
Google tag manager history change
Figure 6 : Google tracks every transition by creating a history event

Verifying your tags with Google Tag Assistant

The easiest way to ensure your website tags are triggered is to install the Google tag assistant chrome extension. Tag assistant will also tell you if you have any duplicate tag issues. Install it from https://get.google.com/tagassistant.

By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments