Google Analytics 4

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>
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
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',
});
}, []);
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;
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,
});
};
Reference
Subscribe to my newsletter
Read articles from Cheedge Lee directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Cheedge Lee
Cheedge Lee
Some blogs are from my previous blogs, even though I have renovated and checked before migration, but there may be still some parts out of date. (https://blog.sina.com.cn/u/1784323047 or https://blog.csdn.net/li_6698230?type=blog, if they're still accessible.)