How to track React websites with Google Analytics 4?

by ervin.williamson , in category: SEO Tools , 6 months ago

How to track React websites with Google Analytics 4?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by dortha , 6 months ago

@ervin.williamson 

To track React websites with Google Analytics 4, follow these steps:

  1. Sign in to your Google Analytics account or create a new one if you haven't already. Make sure you have access to the website you want to track.
  2. In the Admin section of your Google Analytics account, click on "Create Property."
  3. Select "Web" as the property type.
  4. Enter the property details like your website's name, URL, and the time zone.
  5. Click on the "Data Stream" card and select "Web."
  6. Enter the stream details, such as stream name and URL.
  7. Under "Tagging Instructions," select "Set up manually."
  8. Copy the Measurement ID provided in the instructions.
  9. In your React website's code, open the index.js or App.js file (or any other file that holds the main code).
  10. Import the following line at the top of the file:
1
import { useEffect } from 'react';


  1. In the same file, add the following code inside the functional component:
1
2
3
useEffect(() => {
  window.gtag('config', 'YOUR_MEASUREMENT_ID');
}, []);


Make sure to replace 'YOUR_MEASUREMENT_ID' with the Measurement ID copied in step 8.

  1. Save the file, and now your React website is connected to Google Analytics.
  2. To verify if the tracking is working, open your website in a browser. Then, open the browser's developer tools.
  3. Switch to the "Network" tab and filter by "collect" to find the request sent to the Google Analytics server. The request URL should contain "gtm.js" or "gtag/js."
  4. If you see the request, it means the tracking is working correctly, and data will start appearing in Google Analytics.


Note: Google Analytics 4 is a new version, and it has a different measurement model compared to the previous Universal Analytics. Some concepts, reports, and features may differ, so it's recommended to familiarize yourself with the new platform.