Adding Google Tag Manager (GTM) to a React website involves inserting the GTM script into your application. Here's how you can do it:
1. Create a Google Tag Manager Account
If you haven't already, you need to create a Google Tag Manager account and set up a container for your website. Google will provide you with two pieces of code:
- A
<script>
tag that goes in the<head>
of your HTML. - An optional
<noscript>
tag that goes immediately after the opening<body>
tag.
2. Install GTM in Your React App
Option 1: Manually Adding the GTM Code
-
Insert the GTM Script in the
<head>
Tag: In a React app, thepublic/index.html
file is where you'll add the GTM script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
<!-- Google Tag Manager -->
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');
</script>
<!-- End Google Tag Manager -->
</head>
<body>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<div id="root"></div>
</body>
</html>
Replace GTM-XXXXXX
with your actual GTM container ID.
-
Insert the
<noscript>
Tag After the<body>
Tag: Place the<noscript>
tag right after the opening<body>
tag as shown above.
Option 2: Using a React GTM Library
You can also use a React library to simplify the integration.
- Install the GTM Library:
Use npm or yarn to install the react-gtm-module
:
npm install react-gtm-module
- Initialize GTM in Your App:
In your main React component (e.g., App.js
), initialize GTM like this:
import React, { useEffect } from 'react';
import TagManager from 'react-gtm-module';
const App = () => {
useEffect(() => {
const tagManagerArgs = {
gtmId: 'GTM-XXXXXX'
};
TagManager.initialize(tagManagerArgs);
}, []);
return (
<div className="App">
{/* Your app components */}
</div>
);
};
export default App;
Again, replace GTM-XXXXXX
with your actual GTM container ID.
3. Verify Installation
After adding GTM to your React app, publish the changes and verify that the GTM is working by using the Google Tag Assistant Chrome extension or by checking the "Real-time" section in Google Analytics.
Top comments (1)
The react-gtm-module hasn't been maintained in 4 years. The repo appears to be abandon. I suggest find a different method,