React Google Analytics 4

Related tags

React react-ga4
Overview

React Google Analytics 4

Migrate from old react-ga

// Simply replace `react-ga` with `react-ga4`
import ReactGA from "react-ga";
import ReactGA from "react-ga4";

Install

npm i react-ga4

Usage

import ReactGA from "react-ga4";

ReactGA.initialize("your GA measurement id");
ReactGA.send("pageview");

Maintainer

Han Lin Yap

License

MIT

Comments
  • [QUESTION] Best practices for using react-ga4

    [QUESTION] Best practices for using react-ga4

    Instead of copying and pasting a custom event, I have created a utils/ga.js file which is the below. I am just wondering if this would still be ok to use like this?

    import ReactGA from 'react-ga4'
    
    // initialize google analytics
    ReactGA.initialize('G-7XXX')
    
    
    // custom pageview with the location from react router
    export const pageView = path => {
      return ReactGA.send({hitType: 'pageview', page: path})
    }
    
    // custom event with label being an optional parameter
    export const customEvent = (category, action, label = '') => {
      return ReactGA.event({
        category: category,
        action: action,
        label: label,
      })
    }
    

    The use of useLocation here, will this still work? For example if I want to import the function like so:

    import {pageView} from '../utils/ga.js'
    import {useLocation} from 'react-router-dom'
    
    // and use it like 
    let location = useLocation()
    
    pageView(location.pathname)
    

    Would the useLocation hook know the location even though I called it in a different file?

    Also is this a good practice, especially with using the customEvent and calling it like

    import {customEvent} from '../utils/ga.js'
    
    const event = customEvent
    event('somestring', 'some_event')
    
    opened by mrpbennett 6
  • ReactGA.event sends event title with first letter captitalised

    ReactGA.event sends event title with first letter captitalised

    ReactGA initialize, gives options to make the titleCase boolean false. Could such an option be added in react-ga4 as well? image

    So that following code, leads to add_to_cart and not in Add_to_cart?

    ReactGA.initialize( process.env.GA_MEASUREMENT_ID, { gaOptions: { titleCase: false } } );
    ReactGA.event({
          category: "shopping",
          action: "add_to_cart",
          label: "name",
    });
    
    opened by sakshambhatt 6
  • [Doc] Web Vitals Support/Integration

    [Doc] Web Vitals Support/Integration

    Taken from the Web Vitals repository, here is the recommended way to send data to Google Analytics:

    Using gtag.js (Google Analytics 4)

    Google Analytics 4 introduces a new Event model allowing custom parameters instead of a fixed category, action, and label. It also supports non-integer values, making it easier to measure Web Vitals metrics compared to previous versions.

    import {getCLS, getFID, getLCP} from 'web-vitals';
    
    function sendToGoogleAnalytics({name, delta, value, id}) {
      // Assumes the global `gtag()` function exists, see:
      // https://developers.google.com/analytics/devguides/collection/ga4
      gtag('event', name, {
        // Built-in params:
        value: delta, // Use `delta` so the value can be summed.
        // Custom params:
        metric_id: id, // Needed to aggregate events.
        metric_value: value, // Optional.
        metric_delta: delta, // Optional.
    
        // OPTIONAL: any additional params or debug info here.
        // See: https://web.dev/debug-web-vitals-in-the-field/
        // metric_rating: 'good' | 'ni' | 'poor',
        // debug_info: '...',
        // ...
      });
    }
    
    getCLS(sendToGoogleAnalytics);
    getFID(sendToGoogleAnalytics);
    getLCP(sendToGoogleAnalytics);
    

    However the ReactGA.event function does not seem to implement all these fields, could you please look into this and advise on it as sending performances data is really important.

    For more information: https://github.com/GoogleChrome/web-vitals/blob/main/README.md

    Alternatively, if you could provide an example on how to set up the custom dimension and set up the sending of the analytics and add it to the doc, big kudos!

    help wanted 
    opened by aress31 5
  • Why create 200 dimensions & metrics with arbitrary values in custom_map?

    Why create 200 dimensions & metrics with arbitrary values in custom_map?

    Hi there, I am implementing this library but am curious why these lines exists: https://github.com/PriceRunner/react-ga4/blob/0e2e3a624d8c8394438e5ea955f6dabdf01304e4/src/ga4.js#L473-L488

    It creates 10.5kb of JSON that is then sent, and yea, not sure why, or how to stop it from doing so.

    Many thanks.

    documentation enhancement 
    opened by Loque- 3
  • make sure page title shows up on google analytics

    make sure page title shows up on google analytics

    If I only use ReactGA.send("pageview"); I can't see the page views on Google analytics. I had to use ReactGA.send({ hitType: "pageview", page, title: page }); in order to see the page views for different pages on GA.

    opened by NilPuig 2
  • Debug mode

    Debug mode

    Would it be possible to extend this library to allow the use of debug mode? It would be very helpful when testing events on a development branch.

    See below link for more info. https://support.google.com/analytics/answer/7201382?hl=en

    opened by madskchristensen 2
  • Send pageview with a custom path

    Send pageview with a custom path

    hI

    I'm trying this function and simple not working =( ReactGA.send({ hitType: "pageview", page: "/my-path" });

    debugging the issue i just found out that parameters are not passed correctly

    imagen

    or it is just me?

    this is my code

    
    import ReactGA from 'react-ga4';
    import { GOOGLE_ANALYTICS_GA4_ID } from '../api/urlConfig';
    
    export const initGA = () => {
       ReactGA.initialize(
           GOOGLE_ANALYTICS_GA4_ID,
           { debug: true }
           );
    }
    
    export const logPageView = () => {
        ReactGA.set({
            page: window.location.pathname
            
        });
    
        ReactGA.send("pageview");
        // ReactGA.pageview(window.location.pathname);
    };
    
    export const logPageEventCustom = (pageEvent, page) =>{
    
        ReactGA.send({ hitType: "pageview", page: "/my-path" });
       
    };
    
    

    i'm using logPageEventCustom function but the custom route "/my-path" is not appearing

    and this is the console log imagen

    please help

    thanks

    duplicate 
    opened by azielstyle 2
  • Custom event parameters

    Custom event parameters

    Since ga4, events can be sent with custom parameters. The current implementation of ReactGA does not match gtag.

    • Event action is a separate parameter
    • All predefined event parameters (category, label, value, nonInteraction, transport) are not needed. Instead we can send any parameters we need.

    Something like this would match gtag : ReactGA.event('myEvent', { my_param_1: 'my_value_1' })

    https://developers.google.com/tag-platform/gtagjs/reference#event

    enhancement 
    opened by ryancrunchi 2
  • Debug Logging

    Debug Logging

    One of the most useful feature of react-ga is the debugging output to troubleshot issues as follows:

    ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_ID, {
      debug:
        !process.env.NODE_ENV ||
        process.env.NODE_ENV === 'development',
    });
    

    Could you please consider implementing this?

    wontfix 
    opened by aress31 2
  • Event params not being received

    Event params not being received

    Hello, I'm trying to save an login event with the method email, like this: image

    The Data Layer response is: image

    But the Login Method variable is undefined in its table: image

    How can I pass a valid method param?

    opened by arturhaddad 1
  • Not possible to anonymizeIp and location anymore with react-ga4.

    Not possible to anonymizeIp and location anymore with react-ga4.

    Not possible to anonymizeIp and location anymore with react-ga4.

    ReactGA.set({ anonymizeIp: true }) ReactGA.set({ location: 'Anonymized' })

    Doesn't really work with anonymizing

    documentation 
    opened by indhumathi1985 1
  • Upgrade dependencies, add options to specify the script attribute, published fork

    Upgrade dependencies, add options to specify the script attribute, published fork

    meanwhile published the fork to https://github.com/rawpixel-vincent/react-ga4-forked/tree/1.5.4

    reporting issue, feature requests, pull requests welcome

    #53

    opened by rawpixel-vincent 0
  • reason behind custom mapping.

    reason behind custom mapping.

    Hi there, thanks for this library made it easy to migrate to v4.

    I just have one question, what is the reason behind this that you are mapping exactly? There wasn't something like this in react-ga library. Is it necessary?

    image

    opened by alirezavlz 0
  • Ability to set data filters

    Ability to set data filters

    As per GA4 docs it should be possible to set the event parameter traffic_type with the value 'internal'. I guess currently it's not possible to do this with react-ga4.

    I tried adding traffic_type: 'internal' when calling ReactGA.send. However, I noticed that it is making two calls to www.google-analytics.com, one with the passing query string as tt=internal and the other without.

    If this feature is not available, appreciate it if it can be added. Currently, I'm using the testmode option which doesn't really give us what we need.

    opened by kentmz 0
  • default import

    default import "reactGA" import every module _ ES6

    When I try to default import as the usage stated "import 'ReactGA' from 'react-ga4'" ReactGA.initialize('G-0000000000') is not usable and saying it is not a function. error

    in the console.log, it is importing both ReactGAImplementation and default so it can only be initialize through ReactGA.default.initialize(). console_log Is this intended because the usage tutorial is not stated like that

    opened by echo178 0
  • Ecommerce Plugin migration

    Ecommerce Plugin migration

    Hi, first of all, thanks for your job doing this package.

    I would like to know of could I migrate the usage for 'ec' plugin from old reactGA.

    For example:

    ReactGA.plugin.require('ec');
    
    const TRACKERS = [COMPANY_TRACKER, COMMERCE_TRACKER];
    
    TRACKERS.forEach((tracker) => ReactGA.ga(`${tracker}.require`, 'ec'));
    
    // Inside a foreach for products and trackers : 
    ...
    ReactGA.plugin.execute(`${tracker}.ec`, 'addToCart', PRODUCT);
    ...
    ReactGA.plugin.execute(`${tracker}.ec`, 'setAction', 'purchase', PURCHASE);
    
    

    Thank you.

    opened by bastian-hidalgo 0
Releases(v1.4.1)
Owner
PriceRunner
PriceRunner is an independent product and price comparison service
PriceRunner
A web application which is a clone of Google keep. Made it by using react framework.

A web application which is a clone of Google keep. Made it by using react framework.

Shreya Christiana Malogi 13 Oct 30, 2022
Youtube clone with react and google cloud youtube API😊🤘

Getting Started with Create React App This project was bootstrapped with Create React App. UI / Demo Available Scripts In the project directory, you c

Ashutosh Mohanty 5 Apr 14, 2022
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.

Recoil · Recoil is an experimental set of utilities for state management with React. Please see the website: https://recoiljs.org Installation The Rec

Facebook Experimental 18.2k Jan 8, 2023
A Google Clone which built with ReactJS. You can click the demo and search whatever you want!

Google Clone with ReactJS A small web app that imitate the desktop web version of google site, you can search whatever you want. Google Clone Demo Lin

Özge Coşkun Gürsucu 36 Aug 14, 2022
A Facebook Clone which built with reactJS. You can sign in with your Google Account and send realtime posts.

Facebook Clone with ReactJS A Facebook Clone application that you can sign in with your Google Account and send realtime posts. Facebook Clone Demo Li

Mert Çankaya 23 Nov 25, 2022
How to submit HTML forms to Google Sheets. (Updated for 2021 Script Editor)

Submit a HTML form to Google Sheets How to submit a simple HTML form to a Google Sheet using only HTML and JavaScript. Updated for Google Script Edito

Levi Nunnink 314 Jan 6, 2023
Build Google 2.0 with Tailwind CSS & Next.js for Education Purpose..

Paradise of Creativity Parimal Nakrani This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server:

Parimal Nakrani 1 Dec 21, 2021
PWA for making ad hoc room reservations easy in Google Workspace environment.

Get A Room! More images in directory documentation/ui-and-architecture-images! Project structure The project is divided into frontend and backend fold

null 4 Sep 14, 2022
A node script that lists the cities on Santa's route from santatracker.google.com

Google Santa Route A script that lists the cities on Santa's route from santatracker.google.com based on the JSON containing all Santa's destinations.

Emile Calixte 1 Dec 24, 2021
Ember implementation of Google's Material Design

No longer maintained This project is no longer maintained. For an up-to-date material design project, please use Ember Paper. Ember-material-design Th

Mike Wilson 121 Mar 1, 2022
Note Port is a frontend clone of Google Keep. It uses localstorage to save your notes!

Note Port About Note Port is a frontend clone of Google Keep. It uses localstorage to save your notes! Tech Stack React Screenshots Things I want to a

Mohit Dhatrak 3 Sep 10, 2022
Source code for the deprecated expo-google-app-auth package. Deprecated in favor of expo-auth-session.

expo-google-app-auth Source code for the deprecated expo-google-app-auth package. Expo Google App Auth API wrapped the deprecated expo-app-auth packag

Expo 4 Nov 2, 2022
🌐 Unlimited free google translate component & hook

React Native Translator Preview Introduce Free translate component & hook Never need api key, This library is Unlimited free Support translators Googl

Hyun 34 Dec 18, 2022
A new renovated version of Directory to search @expo-google-fonts

Directory | AtilaDev Directory is an easy & quick search to find google fonts using @expo-google-fonts for your React Native App. Usage Press / key to

Leandro Favre 2 Oct 5, 2022
React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Expr

Kriasoft 21.7k Dec 30, 2022
📋 React Hooks for forms validation (Web + React Native)

English | 繁中 | 简中 | 日本語 | 한국어 | Français | Italiano | Português | Español | Русский | Deutsch | Türkçe Features Built with performance and DX in mind

React Hook Form 32.4k Dec 29, 2022
:black_medium_small_square:React Move | Beautiful, data-driven animations for React

React-Move Beautiful, data-driven animations for React. Just 3.5kb (gzipped)! Documentation and Examples Features Animate HTML, SVG & React-Native Fin

Steve Hall 6.5k Jan 1, 2023
React features to enhance using Rollbar.js in React Applications

Rollbar React SDK React features to enhance using Rollbar.js in React Applications. This SDK provides a wrapper around the base Rollbar.js SDK in orde

Rollbar 39 Jan 3, 2023
🎉 toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense!

toastify-react-native ?? toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense! De

Zahid Ali 29 Oct 11, 2022