react-ga4

repository·master·Indexed 43 days ago

https://github.com/codler/react-ga4

A 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.

Tokens
2.6K
Snippets
15
Records
16
Agent score
56%

What's inside react-ga4

  1. Migrate from react-ga to react-ga4

    master

    To migrate from the legacy react-ga package to react-ga4:

    1. Replace the import statement.
    2. Remove any calls to 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";
  2. Send a custom event with ReactGA.event()

    master

    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" });
  3. Extend ReactGA via ReactGAImplementation

    master

    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();
  4. Initialize ReactGA

    master

    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",
      },
    ]);
  5. Configure GA4 via GaOptions

    master

    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'
      }
    });
  6. Reference: ReactGA.event(options) parameters

    master

    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
    })
  7. ReactGA.initialize(GA_MEASUREMENT_ID, options)

    master

    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)
    ParameterTypeNotes
    GA_MEASUREMENT_IDstringRequired
    options.noncestringOptional. Used for Content Security Policy (CSP)
    options.testModebooleanOptional. Default false
    options.gtagUrlstringOptional. Default https://www.googletagmanager.com/gtag/js
    options.gaOptionsobjectOptional
    options.gtagOptionsobjectOptional
  8. Track events with event()

    master

    You can track events using two different signatures:

    1. String signature: Pass a single string as the event name and an optional parameters object.
    2. Object signature: Pass a 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
    });
  9. Set global fields with set()

    master

    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' });