Home >Web Front-end >JS Tutorial >How To Add Google Tag Manager Code in a React Website
Adding Google Tag Manager (GTM) to a React website involves inserting the GTM script into your application. Here's how you can do it:
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:
<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 --> <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>
Replace GTM-XXXXXX with your actual GTM container ID.
You can also use a React library to simplify the integration.
Use npm or yarn to install the react-gtm-module:
npm install react-gtm-module
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.
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.
The above is the detailed content of How To Add Google Tag Manager Code in a React Website. For more information, please follow other related articles on the PHP Chinese website!