How to configure Google Tag Manager for React applications

Author:

Configuring Google Tag Manager (GTM) for a React application requires a few specific steps, as React apps are often single-page applications (SPAs), meaning they do not reload the page when navigating between views. This introduces a few complexities when setting up GTM, especially with event tracking and pageviews. Below is a step-by-step guide on how to set up Google Tag Manager for a React application.

Step 1: Install Google Tag Manager in Your React Application

To get started, you need to add the GTM container code to your React app.

a. Create a Google Tag Manager Account

  1. Go to Google Tag Manager.
  2. Create a new account and container for your website.
  3. You will be given a GTM container code, which looks like this:
    html
    <!-- Google Tag Manager -->
    <script async src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX"></script>
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
    height="0" width="0" style="display:none;visibility:hidden">
    </iframe></noscript>
    <!-- End Google Tag Manager -->

b. Add the GTM Code to Your React App

In your React app, you should inject the GTM code in both the <head> and <body> sections:

  1. Open public/index.html in your React app.
  2. Add the following script just before the closing </head> tag:
    html
    <script async src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX"></script>
  3. Add the <noscript> part right after the opening <body> tag:
    html
    <noscript>
    <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
    height="0" width="0" style="display:none;visibility:hidden">
    </iframe>
    </noscript>

Step 2: Install the react-gtm-module Library (Optional)

While you can manually insert GTM into your React app, using a React-specific module like react-gtm-module simplifies the integration and improves the overall React compatibility.

a. Install the react-gtm-module Library

You can install the react-gtm-module library using npm or yarn:

bash
npm install react-gtm-module

or

bash
yarn add react-gtm-module

b. Configure the Library in Your Application

In your src/index.js or src/App.js, initialize the GTM module as soon as your app loads:

javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { GTMContainer } from 'react-gtm-module';

const gtmId = 'GTM-XXXXXX'; // Replace with your GTM container ID

// Initialize GTM
GTMContainer.initialize({ gtmId });

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>
,
document.getElementById('root')
);

This will set up Google Tag Manager when the app loads, ensuring that it works correctly for all subsequent pageviews and events.

Step 3: Track Pageviews in React (Handling Single-Page App Navigation)

Since React is a single-page application (SPA), it does not reload the page for each new route. Therefore, tracking pageviews with GTM requires you to manually push virtual pageview events to GTM whenever the user navigates to a different route.

a. Use React Router for Navigation

If you’re using React Router to handle navigation in your app, you can listen for route changes and push a pageview event to GTM whenever the user navigates to a new route.

Here’s how to set up the pageview tracking:

  1. Use React Router’s useEffect Hook

In your App.js or another top-level component, import useEffect from React and useLocation from React Router to listen for route changes:

javascript
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { GTMContainer } from 'react-gtm-module';

const App = () => {
const location = useLocation();

useEffect(() => {
// Push the pageview event to GTM whenever the location changes
const pageviewData = {
event: 'pageview',
pagePath: location.pathname,
pageTitle: document.title,
};
GTMContainer.pushDataLayer(pageviewData);
}, [location]);

return (
<div className="App">
{/* Your React app content */}
</div>

);
};

export default App;

This setup ensures that every time the route changes (when the user navigates between different pages), a pageview event is pushed to GTM, including the updated pathname and title.

b. Push Custom Page Events to GTM (Optional)

If you need to track additional custom events (e.g., user interactions, form submissions), you can push events to the GTM data layer like this:

javascript
const handleButtonClick = () => {
const eventData = {
event: 'button_click',
buttonId: 'cta-button',
};
GTMContainer.pushDataLayer(eventData);
};

In this example, a custom event (button_click) is sent to GTM when a user clicks a button with the ID cta-button.

Step 4: Set Up Triggers and Tags in Google Tag Manager

Now that you’ve set up GTM to track pageviews and custom events in your React app, you need to configure your triggers and tags in the GTM interface:

  1. Set up a Pageview Trigger:
    • Go to GTM > Triggers > New.
    • Choose the trigger type Page View and configure it to fire on All Pages.
  2. Set up Custom Event Triggers:
    • Go to GTM > Triggers > New.
    • Choose Custom Event.
    • Set the Event Name to match the event you are pushing to GTM, such as button_click.
  3. Create Tags to Fire Based on These Triggers:
    • For each trigger, create a tag that sends the data to your preferred analytics or tracking platform (e.g., Google Analytics, Facebook Pixel).
    • Example: Create a tag for Google Analytics to track pageviews or custom events.

Step 5: Preview and Publish Your Changes

After setting up the triggers and tags, use GTM’s Preview Mode to test whether your pageviews and custom events are being tracked correctly:

  1. In GTM, click on Preview to enter preview mode.
  2. Open your React app in a new browser tab.
  3. Use the GTM Debugger to verify that the tags are firing when expected (i.e., when navigating between pages or triggering events).

Once you’ve confirmed everything is working correctly, click Publish in GTM to make your changes live.

Conclusion

Setting up Google Tag Manager in a React application involves adding the GTM container code to your app, configuring pageview tracking to handle route changes in a single-page app, and setting up custom event tracking. By using libraries like react-gtm-module and leveraging React Router’s hooks, you can ensure that GTM works seamlessly in your React app. This allows you to track user interactions, monitor performance, and optimize your app based on real-time data from GTM.