Install react-ga4 via npm
masterTo use this library, install it using npm:
npm i react-ga4repository·master·Indexed 43 days ago
https://github.com/codler/react-ga4A React wrapper for Google Analytics 4 (GA4) version 3.0.1 that provides a simplified API to initialize tracking, send pageviews, and dispatch custom events. It includes support for multiple measurement IDs, global field configuration via set(), and custom implementations through the ReactGAImplementation class.
To use this library, install it using npm:
npm i react-ga4To migrate from the legacy react-ga package to react-ga4:
ReactGA.pageview() as they are no longer used in the GA4 version.// Simply replace `react-ga` with `react-ga4` and remove `ReactGA.pageview()`
// import ReactGA from "react-ga";
import ReactGA from "react-ga4";Use ReactGA.send() to send custom pageview data, such as a custom path or title.
ReactGA.send({ hitType: "pageview", page: "/my-path", title: "Custom Title" });You can send events using two different signatures. Note that the options object signature is specifically for GA4 and is NOT for UA-XXX (Universal Analytics).
// Using the options object signature
ReactGA.event({
category: "your category",
action: "your action",
label: "your label", // optional
value: 99, // optional, must be a number
nonInteraction: true, // optional, true/false
transport: "xhr", // optional: 'beacon' | 'xhr' | 'image'
});
// Using the name and params signature
ReactGA.event("event_name", { param1: "value1" });You can extend the core functionality by creating a custom class that inherits from ReactGAImplementation.
import { ReactGAImplementation } from "react-ga4";
class MyCustomOverriddenClass extends ReactGAImplementation {}
export default new MyCustomOverriddenClass();Initialize the library with a single GA measurement ID or an array of multiple products (trackers).
import ReactGA from "react-ga4";
// Single product initialization
ReactGA.initialize("your GA measurement id");
// Multiple products initialization
ReactGA.initialize([
{
trackingId: "your GA measurement id",
gaOptions: {...}, // optional
gtagOptions: {...}, // optional
},
{
trackingId: "your second GA measurement id",
},
]);The GaOptions object allows you to configure how Google Analytics behaves. The library automatically maps these camelCase keys to the snake_case keys required by the gtag.js API.
Key configuration fields:
cookieUpdate: (boolean) Update cookie settings.cookieExpires: (number) Expiration in seconds (default is 2 years).cookieDomain: (string) Domain for cookies.cookieFlags: (string) Additional cookie flags.userId: (string) Set a user ID.clientId: (string) Set a client ID.anonymizeIp: (boolean) Anonymize IP addresses.contentGroup1 through contentGroup5: (string) Content grouping.allowAdFeatures: (boolean) Maps to allow_google_signals.allowAdPersonalizationSignals: (boolean) Maps to allow_ad_personalization_signals.nonInteraction: (boolean) Whether the hit is a non-interaction hit.page: (string) The page path.import ga4 from 'react-ga4';
ga4.initialize('G-XXXXXXXXXX', {
gaOptions: {
userId: 'user_123',
anonymizeIp: true,
contentGroup1: 'blog'
}
});When using the options object signature for ReactGA.event(), use the following parameters:
ReactGA.event({
action: string, // Required
category: string, // Required
label?: string, // Optional
value?: number, // Optional
nonInteraction?: boolean, // Optional
transport?: 'beacon' | 'xhr' | 'image' // Optional
})Initializes Google Analytics 4. You can provide a single string ID or an array of configuration objects for multiple measurement IDs.
```ts
ReactGA.initialize(GA_MEASUREMENT_ID, options)| Parameter | Type | Notes |
|---|---|---|
GA_MEASUREMENT_ID | string | Required |
options.nonce | string | Optional. Used for Content Security Policy (CSP) |
options.testMode | boolean | Optional. Default false |
options.gtagUrl | string | Optional. Default https://www.googletagmanager.com/gtag/js |
options.gaOptions | object | Optional |
options.gtagOptions | object | Optional |
You can track events using two different signatures:
UaEventOptions object containing action, category, and optional label, value, nonInteraction, or transport.Note: When using the object signature, category and action are required. The library uses a format utility to sanitize these strings.
import ga4 from 'react-ga4';
// Using string signature
ga4.event('button_click', { label: 'signup_button' });
// Using object signature (UA-style compatibility)
ga4.event({
action: 'click',
category: 'engagement',
label: 'header_nav',
value: 1,
nonInteraction: true
});Use set() to update global fields in the Google Analytics configuration. This is useful for setting properties that should persist across all subsequent hits (like user properties or custom dimensions).
import ga4 from 'react-ga4';
// Set a global user property
ga4.set({ user_type: 'premium' });