DEV Community

Cheedge Lee
Cheedge Lee

Posted on • Originally published at notes-renovation.hashnode.dev

How to add GA4 to your React app

1. create a new propety

In Analytics your account Dashboard, click the left corner gear icon (Admin). Then "Create" -> "property".
After created, it will give a pice of js script for the Google tag.
Add this pice of code to the react index.html file, under .

    <head>
        <!-- Google tag (gtag.js) -->
        <script
            async
            src="https://www.googletagmanager.com/gtag/js?id=YOURGA4MEASUREID"
        ></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag() {
                dataLayer.push(arguments);
            }
            gtag('js', new Date());

            gtag('config', 'YOURGA4MEASUREID');
        </script>
        <title>Vite+React</title>
    </head>
Enter fullscreen mode Exit fullscreen mode

after this it will also gives you a MEASUREMENT_ID, which used for initialization in the code.
Or in Admin, under Data collection and modification, click Data streams.[1]

2. react-ga4

Install react-ga4

npm install react-ga4
Enter fullscreen mode Exit fullscreen mode

3. Initialize

In the Start code (eg. App.js or your own StartPage.js) initialize the GA4.

    useEffect(() => {
        // Initialize Google Analytics
        ReactGA.initialize(TRACKING_ID);
        ReactGA.send({
            hitType: 'pageview',
            page: 'PAGEYOUNEED',
        });
    }, []);
Enter fullscreen mode Exit fullscreen mode

4. Define your own event

Next define some events, for example, we want to track when user click the button.

import React from 'react';
import ReactGA from 'react-ga4';

function MyComponent() {
  const trackButtonClick = () => {
    ReactGA.event({
      category: "Button",
      action: "Click",
      label: "Submit Button",
    });
    // Perform button's action
    alert("Button Clicked")
  };

  return (
    <button onClick={trackButtonClick}>Submit</button>
  );
}

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

Use the ReactGA.event() method to track events on the Page you want. This method accepts an object with the following properties:

  • category: The category of the event (e.g., "User", "Product", "Form").
  • action: The action that was performed (e.g., "Login", "Add to Cart", "Submit").
  • label (optional): A label for the event (e.g., "Newsletter Signup").
  • value (optional): A numerical value associated with the event.
  • nonInteraction (optional): A boolean to indicate if the event is a non-interaction event. Defaults to false

5. Addition

You can directly use the react-ga4 command in code, but better to use a separated file for all these. for example you can define a logEvent to use for different Event use later.

export const logEvent = (category, action, label) => {
    ReactGA.event({
        category,
        action,
        label,
    });
};
Enter fullscreen mode Exit fullscreen mode

Reference

[1][GA4] Measurement ID

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more