Google Tag Manager, Google Analytics & React — Integration & Examples

Lokendra Lodha
8 min readFeb 16, 2021

This article covers integration of React based application with Google Tag Manager. The Google Tag Manager setups in this article sends the page views and events tags to Google Analytics for your application analysis. However these informations can be sent to N number of channels.

The following use-cases are showcased in the article:

  1. All Pages routed via React router (React-router-dom )
  2. All External links clicked
  3. Custom events on any button clicks, form submit success and error cases:

Integrate: GA & Google Tag manager on each page and major activities:

Sign-in Email

Sign-in Google

Sign-in Error

Sign-in Success

Get Help

Free Trial

Forgot Password

ViewPager Visits (Each Page)

Google Analytics — Setups

Go to your Google Analytics Account

- Create google analytics property of type Universal Analytics

- Note down your Universal property ID with prefix UA-***

Google Tag Manager — Setups

  1. Register your Google Tag Manager account at: https://tagmanager.google.com/
  2. For each company you than need to create a separate container

3. Finally access your container dashboard. It looks similar to this:

  • * NOTE: You will see 0 tags initally.
  • So now lets define the variables, triggers and the tags
[ Tags Screen]

BASICS

We assume you know on Google Tag Manager basics and — Summarizing there are Tags, Triggers and Variables

Variables: we need to define the data definitions — using one or more: 1. built in variables or 2. custom data types . These are called variables.

Example:

Simple variables: Define your google analytics property in some variable.

Variables for data mapping: example — eventLabel , eventAction can be defined as variables and finally mapped to google analytics — events as label & action.

Triggers: Triggers identifies the source of events, such as on click of links, on submit of form, on history change , on external links clicked etc. We create the triggers and these in turn fires the events to GTM for consumptions

For example, fire an event on click of button clicks with a specific CSS class.

Tags: Tag definition binds a tag (such as your google analytics destination property, or a slack channel) and the matching events rules. So whenever a matching event triggers, the GTM shall auto forward the event information to your destination tag.

Let’s 1st Add your Google Analytics tracking code to Google Tag Manager

We define a custom user defined variable to bind the Google Analytics tag (tracking code) with a variable name.

As noted above Go to GTM -> Variables section

Click on NEW btn in User-Defined Variables section

Add the variable with name : Google Analytics UA settings

Set the tracking ID value to to Google Analytics tracking code…

As mentioned in above [Tags screen] we have defined 3 main tags below :

  1. App Custom Events Tag: To track all custom events such as login submit success/errors
  2. App Track All External Links Click: To track all external links clicks that outbounds from our webpage to a 3rd party or external website. Such as Get Help page or (for example to Amazon product detail pages,….)
  3. App Track All History Change Tag: To track every page changes via the react router. Each change shall be visible as a page view in Google analytics

App Custom Events Tag:

To track all custom events such as login submit success/errors

1st define the 4 custom user defined variables: of type Data Layer Variable

Go to GTM -> Dashboard -> Variables

Let’s name these as eventCategory , eventAction, eventLabel and eventValue

To create a variable there is a ‘NEW’ variable button at extreme right of User-Defined Variables section:

Define Custom Event Based Trigger, which shall fire the custom events triggers

Got to GTM -> Triggers

and add a Trigger named: App Custom Event Trigger

Choose the Trigger Configuration -> Trigger Type as Custom Event

Select the “All Custom Events” for radio options: This triggers fires on.

Define the Tag to bind your Google Analytics with the above defined:

google analytics variables , event trigger and event variables:

  1. Tag Type: choose Google Analytics Universal Analytics
  2. Target type: Event
  3. Category: choose variable {{eventCategory}}
  4. Action: choose variable {{eventAction}}
  5. Label: choose variable {{eventLabel}}
  6. Google Analytics settings: choose variable {{Google Analytics UA settings}}

So, our App Custom Events Tag is ready for preview and testing!!

App Track All External Links Click:

To track all external links clicks that outbounds from our webpage to a 3rd party or external website. Such as Get Help page or (for example to Amazon product detail pages,….)

Define a variable named: IsOutbound

Go to GTM -> Variables and click NEW

Choose the Variable Type as: Auto-Event Variable

Choose the 2nd Variable Type as: Element URL

Choose the Component Type: Is Outbound

** Is Outbound specifies this is for external links

Define the App External Links Click Trigger:

  • Choose Target Type as: Just Links
  • Choose Wait for Tags as : 2000

Choose Page URL as matches RegEX and value as :

.*

since we want all external links clicked to be matched.

Choose the Fire this trigger when an Event occurs and all of these conditions are true — as: Some Link Clicks

and select IsOutbound equals true

Define the Tag to bind your Google Analytics with the above defined configurations:

  1. Tag Type: choose Google Analytics Universal Analytics
  2. Target type: Event
  3. Category: choose static text “External Link Click”
  4. Action: choose in-built variable {{Click URL}}
  5. Label: choose in-built variable {{click Text}}
  6. Google Analytics settings: choose variable {{Google Analytics UA settings}}

So, our App Track External Links Click Tag is ready for preview and testing!!

App Track All History Change Tag:

To track every page views with-in the react app. i.e. whenever the react router performs a history changes. Each change shall be visible as a page view in Google analytics….

Go to GTM -> Tag -> NEW

  1. Tag Type: choose Google Analytics Universal Analytics
  2. Target type: Pageview
  3. Google Analytics settings: choose variable {{Google Analytics UA settings}}
  1. Choose Firing Triggers as the pre-defined Trigger Type: History Change
  2. Choose this triggers fires on: All History Changes

So, our App Track All History Change Tag is ready for preview and testing!!

React Project — Installations & Setups

We are going to use the react-gtm-module npm module for Google Tag Manager integration:

https://github.com/alinemorelli/react-gtm#readme

$ yarn add react-gtm-module

React Project — Define a React Class for to:

initialize the Google Tag Manager

handle the pageviews

handle custom events such as form submits success/errors

Concrete Interface Driven Class to initialize and send analytics data

The interface exported is called Tracker and has 3 main functions: init, pageview and event.

These are binded with actual GTM implementations GTM_Tracker which has: GTM_PageView, GTM_PageView & GTM_Event

The interface driven approach allows us to change the implementation in future if we want to switch between next versions of Google Tag Manager or to a different alternatives.

Sample custom history : util/history.js

import { createBrowserHistory } from ‘history’

export default createBrowserHistory()

Sample util/analytics.js

import ReactGA from ‘react-ga’;

import TagManager from ‘react-gtm-module’

import history from ‘./history’;

const tagManagerArgs = {

// Change your GTM tracking code below.

gtmId: ‘GTM-*********’

}

const GTM_initGA = () => {

TagManager.initialize(tagManagerArgs)

var self = this;

history.listen((location) => {

if(location.pathname.includes(‘/user’)) {

let rootURL = location.pathname.split(‘/’)[1]

let userPage = location.pathname.split(‘/’)[3]

let pageHit = `/${rootURL}/${userPage}`

self.GTM_PageView({page:pageHit})

} else {

self.GTM_PageView(false)

console.log(“page event sent :”+location.pathname)

}

});

}

const GTM_PageView = (params) => {

//nothing to be done here .. as we use on GTM History Change variable to track all router page changes

if(params && params.page){

//

}else{

//

}

}

/**

* Event — Add custom tracking event.

* @param {string} category

* @param {string} action

* @param {string} label

*/

const GTM_Event = (category, action, label) => {

const tagManagerArgs = {

dataLayer: {

event:’appEvent’,

eventCategory: category,

eventAction: action,

eventLabel: label

},

}

TagManager.dataLayer(tagManagerArgs)

};

const GTM_Tracker ={

init:GTM_initGA,

pageview:GTM_PageView,

event:GTM_Event

}

export const Tracker = GTM_Tracker;

Let’s now write the custom events and send the events to GTM

Simply call:

Tracker.event(……..)

i.e. Tracker.event(<event category>, <event action>,<event label>)

Usecase: On login submit success and login submit failure

We have a redux saga function which handles the login:

//SAGA FUNCTION

export function* postLogin(action) {

console.log(action, “SAGA PostLogin”);

let requestURL = API_ENDPOINTS.login;

const options = {};

options.headers = {

‘Content-Type’: ‘application/json’,

};

options.method = ‘POST’;

options.body = JSON.stringify(action.payload);

try {

// const { email, password } = action.payload;

const response = yield call(requestPromise, requestURL, options);

console.log(response, “SAGA postLogin After Yield Response”);

yield put(actions.loginSuccess(response, options.method));

if (response && response.s !== ‘200’) {

action.onSuccess(response);

}

Tracker.event(“AUTH”, “login”, “login-success”)

} catch (error) {

Tracker.event(“AUTH”, “login”, “login-failed”)

action.onError({ s: “500”, m: “Login failed!”, error: error });

}

}

Configure your main app class for Tracker initialization:

import {Tracker} from ‘./util/analytics’;

Tracker.init()

Configure your router to use custom history class:

import history from ‘./util/history’;

export function Routes() {

return (

<Router history={history} >

That’s it.

We can now verify the pageviews and custom events using Google Tag Manager Preview or Live modes.

You can use Google Analytics — Real Time Modes to see the various received analytics informations — the page views and the events

Sample Google Analytics Previews:

--

--