### Initialize and Configure ReactGA4 Source: https://github.com/codler/react-ga4/blob/master/README.md Examples for initializing the library with a single measurement ID or multiple trackers, and migrating from react-ga. ```javascript // Migrate from react-ga import ReactGA from "react-ga4"; // Initialize with single ID ReactGA.initialize("your GA measurement id"); // Initialize with multiple trackers ReactGA.initialize([ { trackingId: "your GA measurement id", gaOptions: {}, gtagOptions: {} }, { trackingId: "your second GA measurement id" } ]); ``` -------------------------------- ### Install react-ga4 library Source: https://github.com/codler/react-ga4/blob/master/README.md Command to install the react-ga4 package via npm. ```bash npm i react-ga4 ``` -------------------------------- ### ReactGA.initialize Reference Source: https://github.com/codler/react-ga4/blob/master/README.md Reference for the ReactGA.initialize method, detailing its parameters and options. ```APIDOC ## ReactGA.initialize(GA_MEASUREMENT_ID, options) ### Parameters - **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. For GA options. - **options.gtagOptions** (object) - Optional. For gtag options. ``` -------------------------------- ### Extend ReactGA Implementation Source: https://github.com/codler/react-ga4/blob/master/README.md How to create a custom class by extending the base ReactGAImplementation. ```javascript import { ReactGAImplementation } from "react-ga4"; class MyCustomOverriddenClass extends ReactGAImplementation {} export default new MyCustomOverriddenClass(); ``` -------------------------------- ### Multiple Trackers Initialization Source: https://github.com/codler/react-ga4/blob/master/README.md Initialize react-ga4 with multiple trackers, each with its own configuration. ```javascript ReactGA.initialize([ { trackingId: "your GA measurement id", gaOptions: {...}, // optional gtagOptions: {...}, // optional }, { trackingId: "your second GA measurement id", }, ]); ``` -------------------------------- ### Basic Initialization Source: https://github.com/codler/react-ga4/blob/master/README.md Initialize react-ga4 with your Google Analytics Measurement ID. ```javascript import ReactGA from "react-ga4"; ReactGA.initialize("your GA measurement id"); ``` -------------------------------- ### Migrate react-ga to react-ga4 Initialization and Tracking Source: https://context7.com/codler/react-ga4/llms.txt Demonstrates the code changes required to migrate from 'react-ga' to 'react-ga4'. This includes updating the initialization process and adapting page view and event tracking methods. GA4 automatically tracks page views, so manual tracking might be removed or adjusted using the 'send' method. ```javascript // Before (react-ga) // import ReactGA from 'react-ga'; // ReactGA.initialize('UA-XXXXXXXX-X'); // ReactGA.pageview(window.location.pathname); // After (react-ga4) import ReactGA from "react-ga4"; ReactGA.initialize("G-XXXXXXXXXX"); // Note: Remove ReactGA.pageview() - GA4 automatically tracks page views // Or use send() for manual pageview tracking: ReactGA.send({ hitType: "pageview", page: window.location.pathname }); // Event tracking remains similar // Before: ReactGA.event({ category: 'User', action: 'Login' }); // After (same syntax works): ReactGA.event({ category: "User", action: "Login" }); // Or use the new GA4-style events: ReactGA.event("login", { method: "Email" }); ``` -------------------------------- ### Extend ReactGAImplementation for Custom Logic Source: https://context7.com/codler/react-ga4/llms.txt Demonstrates how to subclass ReactGAImplementation to inject custom middleware, logging, or data enhancement logic into the initialization and event tracking processes. ```javascript import { ReactGAImplementation } from "react-ga4"; class CustomGA4 extends ReactGAImplementation { event = (optionsOrName, params) => { const enhancedParams = typeof optionsOrName === "string" ? { ...params, timestamp: Date.now() } : optionsOrName; super.event(optionsOrName, enhancedParams); }; } const customGA = new CustomGA4(); export default customGA; ``` -------------------------------- ### ReactGA.ga(...args) Source: https://context7.com/codler/react-ga4/llms.txt Provides access to the legacy Universal Analytics command queue interface for easier migration. ```APIDOC ## ReactGA.ga(...args) ### Description Provides access to the legacy Universal Analytics command queue interface for easier migration from react-ga. Supports both command strings and callback functions. ### Method N/A (Client-side Method) ### Parameters #### Request Body - **args** (arguments) - Required - Variable arguments representing UA-style commands (e.g., 'send', 'set'). ### Request Example ReactGA.ga("send", "event", "Category", "Action", "Label", 100); ``` -------------------------------- ### Initialize Google Analytics 4 Source: https://context7.com/codler/react-ga4/llms.txt Configure the GA4 instance using a measurement ID. This must be called before any tracking events are sent. ```javascript import ReactGA from "react-ga4"; // Basic initialization with a single measurement ID ReactGA.initialize("G-XXXXXXXXXX"); // Initialize with options ReactGA.initialize("G-XXXXXXXXXX", { testMode: true, nonce: "abc123", gtagUrl: "https://www.googletagmanager.com/gtag/js", gaOptions: { cookieUpdate: false, cookieDomain: "example.com", cookieExpires: 63072000, userId: "user-123", anonymizeIp: true, }, gtagOptions: { send_page_view: false, }, }); // Initialize multiple measurement IDs ReactGA.initialize([ { trackingId: "G-XXXXXXXXXX", gaOptions: { userId: "user-123" }, gtagOptions: { debug_mode: true }, }, { trackingId: "G-YYYYYYYYYY", gaOptions: { anonymizeIp: true }, }, ]); ``` -------------------------------- ### Execute Legacy UA Commands with ReactGA.ga Source: https://context7.com/codler/react-ga4/llms.txt Provides access to the Universal Analytics command queue interface, facilitating migration from older implementations. It supports standard command strings and callback functions to retrieve tracker state. ```javascript import ReactGA from "react-ga4"; ReactGA.ga("send", "pageview"); ReactGA.ga("send", "event", "Category", "Action", "Label", 100); ReactGA.ga((tracker) => { const clientId = tracker.get("clientId"); console.log("Client ID:", clientId); }); ``` -------------------------------- ### ReactGA.send Reference Source: https://github.com/codler/react-ga4/blob/master/README.md Reference for the ReactGA.send method, used to send hits. ```APIDOC ## ReactGA.send(fieldsObject) ### Parameters - **fieldsObject** (object) - Required. An object containing fields for the hit. ``` -------------------------------- ### ReactGA.set Reference Source: https://github.com/codler/react-ga4/blob/master/README.md Reference for the ReactGA.set method, used to set dimension values. ```APIDOC ## ReactGA.set(fieldsObject) ### Parameters - **fieldsObject** (object) - Required. An object containing fields to set. ``` -------------------------------- ### ReactGA.gtag(...args) Source: https://context7.com/codler/react-ga4/llms.txt Provides direct access to the underlying gtag() function for advanced use cases. ```APIDOC ## ReactGA.gtag(...args) ### Description Provides direct access to the underlying gtag() function for advanced use cases not covered by the higher-level API. Allows sending any gtag command directly. ### Method N/A (Client-side Method) ### Parameters #### Request Body - **args** (arguments) - Required - Variable arguments passed directly to the gtag function. ### Request Example ReactGA.gtag("event", "share", { method: "Twitter", content_type: "article" }); ``` -------------------------------- ### ReactGA.event Reference (Custom Event) Source: https://github.com/codler/react-ga4/blob/master/README.md Reference for sending custom events using the event method with an options object. ```APIDOC ## ReactGA.event(options) ### Parameters - **options** (object) - Required. - **options.action** (string) - Required. - **options.category** (string) - Required. - **options.label** (string) - Optional. - **options.value** (number) - Optional. Must be a number. - **options.nonInteraction** (boolean) - Optional. - **options.transport** (string) - Optional. Can be 'beacon', 'xhr', or 'image'. ``` -------------------------------- ### Send Pageviews and Events Source: https://github.com/codler/react-ga4/blob/master/README.md Methods for tracking user interactions and page views within a React application. ```javascript // Send pageview with a custom path ReactGA.send({ hitType: "pageview", page: "/my-path", title: "Custom Title" }); // Send a custom event ReactGA.event({ category: "your category", action: "your action", label: "your label", value: 99, nonInteraction: true, transport: "xhr" }); ``` -------------------------------- ### Integrate Web Vitals Performance Tracking Source: https://context7.com/codler/react-ga4/llms.txt Connects the web-vitals library to Google Analytics 4 to track performance metrics like CLS, FID, and LCP. It maps performance data to GA4 events for detailed analysis. ```javascript import ReactGA from "react-ga4"; import { onCLS, onFID, onLCP } from "web-vitals"; function sendToGoogleAnalytics({ name, delta, id, rating }) { ReactGA.send({ hitType: "event", eventCategory: "Web Vitals", eventAction: name, eventLabel: id, value: Math.round(name === "CLS" ? delta * 1000 : delta), metric_rating: rating }); } onCLS(sendToGoogleAnalytics); onFID(sendToGoogleAnalytics); onLCP(sendToGoogleAnalytics); ``` -------------------------------- ### Set Persistent Properties with ReactGA.set Source: https://context7.com/codler/react-ga4/llms.txt Configures persistent values such as user properties, content groups, and page-level metadata that are included in all subsequent tracking hits. This method ensures consistent data across multiple events. ```javascript import ReactGA from "react-ga4"; ReactGA.set({ userId: "user-12345", anonymizeIp: true, }); ReactGA.set({ contentGroup1: "Blog", contentGroup2: "Technology", contentGroup3: "React", }); ReactGA.set({ page: "/home", referrer: "/signup", }); ReactGA.set({ allowAdFeatures: false, allowAdPersonalizationSignals: false, }); ``` -------------------------------- ### Send Pageview Source: https://github.com/codler/react-ga4/blob/master/README.md Send a pageview hit to Google Analytics, optionally with a custom path and title. ```javascript ReactGA.send({ hitType: "pageview", page: "/my-path", title: "Custom Title" }); ``` -------------------------------- ### Track Custom Events Source: https://context7.com/codler/react-ga4/llms.txt Log custom user interactions using either the modern GA4 event structure or the legacy Universal Analytics category/action/label format. ```javascript import ReactGA from "react-ga4"; // Modern GA4 recommended events ReactGA.event("screen_view", { app_name: "myApp", screen_name: "Home", }); ReactGA.event("purchase", { transaction_id: "T12345", value: 99.99, currency: "USD", items: [ { item_id: "SKU_12345", item_name: "Product Name", price: 99.99, quantity: 1 } ], }); // Legacy Universal Analytics style ReactGA.event({ category: "User", action: "Login", label: "Google OAuth", value: 1, nonInteraction: true, transport: "beacon", }); ``` -------------------------------- ### Advanced Tracking with ReactGA.gtag Source: https://context7.com/codler/react-ga4/llms.txt Enables direct interaction with the underlying gtag() function for advanced configurations like consent mode or custom event parameters that exceed the standard library API capabilities. ```javascript import ReactGA from "react-ga4"; ReactGA.gtag("event", "share", { method: "Twitter", content_type: "article", }); ReactGA.gtag("consent", "update", { analytics_storage: "granted", }); ``` -------------------------------- ### ReactGA.set(fieldsObject) Source: https://context7.com/codler/react-ga4/llms.txt Sets persistent values that will be sent with all subsequent hits, such as user properties or content groups. ```APIDOC ## ReactGA.set(fieldsObject) ### Description Sets persistent values that will be sent with all subsequent hits. Useful for setting user properties, content groups, or other configuration that should apply to all tracking calls. ### Method N/A (Client-side Method) ### Parameters #### Request Body - **fieldsObject** (object) - Required - An object containing key-value pairs of properties to set. ### Request Example { "userId": "user-12345", "anonymizeIp": true } ``` -------------------------------- ### Send Custom Event Source: https://github.com/codler/react-ga4/blob/master/README.md Send a custom event to Google Analytics with category, action, and optional parameters. ```javascript 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 }); ``` -------------------------------- ### Send Pageview Hits Source: https://context7.com/codler/react-ga4/llms.txt Track page views by sending hit objects to Google Analytics. This is essential for monitoring user navigation paths. ```javascript import ReactGA from "react-ga4"; // Send a basic pageview ReactGA.send("pageview"); // Send pageview with custom path and title ReactGA.send({ hitType: "pageview", page: "/my-path", title: "My Page Title" }); // Send pageview with location ReactGA.send({ hitType: "pageview", page: "/products/shoes", title: "Shoes Collection", location: "https://example.com/products/shoes", }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.