Giter VIP home page Giter VIP logo

react-ga4's People

Contributors

codler avatar mformarlon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-ga4's Issues

[Help] ReactGA.Send command doesn't work

I have the following code in my React app:

import { useEffect} from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga4";

const usePageTracking = () => {
  const location = useLocation();

  useEffect(() => {
    ReactGA.initialize("G-XXXXXXXXX");
    const path = location.pathname + location.search;
    console.log(path);
    ReactGA.send({ hitType: "pageview", page: path});
  }, [location]);
};

export default usePageTracking;

The console.log prints correctly (/home) but nothing logs on firebase events panel, the only events I see are: first_visit and session_start.

The Live users in the last 30 minutes works fine.

Am I missing something?

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

OutboundLink

@codler how to track OutboundLink with target: '_self'
GA event get cancelled if user redirect on same tab .
need help .thanks in advance.

Event processing aborted.

Hi, first of all, thanks for the support and dedication ๐Ÿ‘๐Ÿป

Context:

Since I moved from react-ga to react-ga4 I stopped to receive any data and debugging it with browser extension I realized about it on ReactGA initialization with ga4 meassure-id "G-XXXXXXX". I only receive "Event processing aborted".

import ReactGA from 'react-ga4';

const TrackingID: string = "G-XXXXXXXX";

ReactGA.initialize(TrackingID, {
  testMode: false,
  gaOptions: {
    titleCase: false,
    cookieFlags: "SameSite=None; Secure",
  }
});

Screenshot 2022-06-19 at 16 22 03

Question:

Does anyone know which is the main problem with this initialization?

Thank you all.

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

Fix types

Problem

There are several problems with typings

Somewhere you put any like in this example

* @property {GaOptions|any} [gaOptions]

Niether put any types like here
send = (fieldObject) => {

So then it becomes any anyway.
This is the opposite of what typings are for.

Solution

In my opinion, it's better to rewrite the script in ts, so it's easier to maintain types, or eventually put right types everywhere

Equivalent to gtag set

how can I set a property like this?

gtag('set', 'user_properties', { 'user_Id' : '12345' });

something like this:
ReactGA.set( {
'user_properties': { 'user_Id' : '12345' }
} );

Default Initialize command for GA4

Hi,

I am trying to use react-ga4 on a brand new site with GA4. I have no previous UA requirements. The current initialize command is not transparent enough and seems to default to legacy settings. For example, if I just call GA4.initialize("MY_MEASUREMENT_ID") the following command is sent:

Processing GTAG command: ["config", "MY_MEASUREMENT_ID", {send_page_view: false, custom_map: {dimension1: "dimension1", metric1: "metric1", ..., metric200: "metric200"}}]

There is no documentation on what legacyDimensionMetric does but if call GA4.initialize("MY_MEASUREMENT_ID", { legacyDimensionMetric: false }) then this command is sent:

Processing GTAG command: ["config", "MY_MEASUREMENT_ID", {send_page_view: false}]

So by default the current initialize command overrides the default send_page_view setting according to https://developers.google.com/analytics/devguides/collection/gtagjs/pages#manual_pageviews

The only way around this appears to be manually setting send_page_view to true by calling GA4.initialize("MY_MEASUREMENT_ID", { legacyDimensionMetric: false, gtagOptions: { send_page_view: true } }) which results in the following command being sent:

Processing GTAG command: ["config", "MY_MEASUREMENT_ID", {send_page_view: true}]

This works but it would be great if there was a separate initialize command or an option to initialize using the default command only with no additional config info as per Google documentation i.e. gtag('config', 'MY_MEASUREMENT_ID').

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:

react-ga4/src/ga4.js

Lines 473 to 488 in 0e2e3a6

_appendCustomMap(options) {
if (!options.custom_map) {
options.custom_map = {};
}
for (let i = 1; i <= 200; i++) {
if (!options.custom_map[`dimension${i}`]) {
options.custom_map[`dimension${i}`] = `dimension${i}`;
}
if (!options.custom_map[`metric${i}`]) {
options.custom_map[`metric${i}`] = `metric${i}`;
}
}
return options;
}

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.

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",
});

sending pageview with custom path

Thanks for the package, got me out of a tight spot.

The .pageview() method is deprecated, but .send('pageview') doesn't obviously allow me to include a custom path.

Help Appreciated.

[Doc] OutboundLink

OutboundLink is marked as deprecated and I am not sure what method to use instead and how to do. Would you please mind adding in the doc how/what to do? :)

The signature '({ label }: { label: string; }, hitCallback: Function): void' of 'ReactGA.outboundLink' is deprecated.ts(6387)
ga4.d.ts(87, 8): The declaration was marked as deprecated here.
(method) GA4.outboundLink({ label }: {
    label: string;
}, hitCallback: Function): void
@since โ€” v1.0.6
@param options
@param hitCallback
@deprecated

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.

Unset GTag

Hi,

I was wondering if we have a way to unset gtag once set?

    ReactGA.gtag('set', 'user_properties', {
      app_uuid: userDetails.uuid,
    });

Related #18

Unable to set event-scoped custom dimension that applies to all sessions and events

There is a similar issue reported here. However, the suggested solution only addresses user-scoped custom dimensions.

Also, the documentation for ReactGA.event(options) suggests that dimension and metric can be passed in but this is not correct as the expected parameter is of type UaEventOptions.

    export type UaEventOptions = {
        action: string;
        category: string;
        label?: string;
        value?: number;
        nonInteraction?: boolean;
        transport?: ('beacon' | 'xhr' | 'image');
    };

Predefined Ecommerce Event Tracking

Hi,

I wonder how to use this package to track predefined events for ecommerce.

so based on Google Documentation, the datalayer object that being sent to GTM should follow the format as below:

datalayer.push({
'event': 'view_item_list' // predefined event for ecommerce,
'ecommerce': {
   'items': [_array_of_items_]
}
});

also whenever we push new ecommerce object to the datalayer, we must first clear up the previous object, with the following code:

dataLayer.push({ ecommerce: null }); 

any idea how to achieve this using React-ga4 package?

Invalid event parameter "_ipe" on event "page_view", parameter will not be logged

I am getting errors in console with Google Analytics Debugger Chrome Extension:

_Invalid event parameter "ipe" on event "page_view", parameter will not be logged

for

ReactGA.send({ hitType: 'pageview', page: '/' });

and

_Invalid event parameter "ipe" on event "Action", parameter will not be logged

for

// Send a custom event
ReactGA.event({
  category: 'category',
  action: 'action',
  label: 'label', // optional
  value: 99, // optional, must be a number
  nonInteraction: true, // optional, true/false
  transport: 'xhr', // optional, beacon/xhr/image
});

I have tried other ways like directly adding script as the provided screenshot. But still errors in console. You can see the errors in the screenshot:

Screenshot link: https://i2.paste.pics/718a0667b24f092a050dd591c0dc663b.png

Please help

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?

Not receiving any data to Google Analytics, debugger extension shows no information in console

I made the following wrapper component to enable google analytics in my react app. However it doesn't appear to work at all. Google Analytics isn't detecting any page views or anything. There is nothing in the Chrome inspector logs even when I activate the Google Analytics Debugger extension. What am I doing wrong?

import { useEffect } from "react";
import ReactGA from "react-ga4";
import { useLocation } from "react-router-dom";

ReactGA.initialize("G-__MYCODEHERE___", { debug: true });

export default function GoogleAnalytics({ children }) {
  const location = useLocation();
  useEffect(() => {
    const currentPath = location.pathname + location.search;
    ReactGA.send({ hitType: "pageview", page: currentPath });
  }, [location]);
  return <>{children}</>;
}

[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')

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

all event properties are required

label,
value,
nonInteraction,
transport

Are all required event values for some reason. I think they should only be optional.

event: ({ category, action, label, value, nonInteraction, transport, ...args }?: {
        category: any;
        action: any;
        label?: any;
        value?: any;
        nonInteraction?: any;
        transport?: any;
    }) => void;

gtagOptions doesn't work

The example in the readme shows:

ReactGA.initialize([
  {
    trackingId: "your GA measurement id",
    gaOptions: {...}, // optional
    gtagOptions: {...}, // optional
  },
  {
    trackingId: "your second GA measurement id",
  },
]);

But it appears to me that setting gtagOptions here does not work. I think it is a bug on this line:

...config.gaOptions,

Should that be config.gtagOptions ...?

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

Unable to set custom dimension that applies to all sessions and events

Hi,

I am trying to add a custom dimension onto all sessions and events of my React SPA site. What I would like is for the user name to be put as the custom dimension so that I can track user sessions and events.

I had this previously set up in UA using the react-ga npm package. With the old set up I used

ReactGA.set({
                dimension1: x.loginName
            })

This then set the login name against the session and any events.

I have now implemented GA4 on the site and using this npm package. I have set up the custom dimension named "currentUser" with the user scope in GA.

Note: I am entering the react-ga4 package like

import { default as ReactGA4 } from "react-ga4";
Within the code I have entered the below

ReactGA4.set({
                    currentUser: x.loginName
            })

And also

ReactGA4.gtag('set', 'user_properties', { 'currentUser': x.loginName });

How can I set this dimension at the start of a user session? I can see the sessions coming through, however the custom dimension is not set

gaOptions not setting secure cookie flag?

From what I understand in the readme:

ReactGA.initialize([
  {
    trackingId: "your GA measurement id",
    gaOptions: {...}, // optional
    gtagOptions: {...}, // optional
  },
  {
    trackingId: "your second GA measurement id",
  },
]);

you should be able to set gaOptions, within those options based on the typing library you should be able to set cookie flags as a string:
https://github.com/PriceRunner/react-ga4/blob/master/types/ga4.d.ts#:~:text=cookieFlags%3F%3A%20string%3B

export type GaOptions = {
...
...
    cookieFlags?: string;
...

Settings cookie flags as such does not properly set the secure cookie flag:

      ReactGA.initialize(trackingID, {
        gaOptions: { cookieFlags: 'secure;samesite=none' },
      });

Is this issue similar to the original ReactGA library's issue with setting cookie flags here?
react-ga/react-ga#423

I have tried with different formatting and convention of the cookie flag, such as this capitalization format of the cookie flag without success:

gaOptions: { cookieFlags: 'SameSite=None; Secure' },

[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!

testMode does not print anything in the console.log

Hi, thanks for the work on migrating the react-ga to GA4

I'm trying to use this one, but cant get it to work or print anything in the console:

This is my custom hook:


const TRACKING_ID = 'G-XXXXXXX';

browserHistory.listen((location) => {
  ReactGA.set({ page: location.pathname });
  ReactGA.pageview(location.pathname);
});

export const useGA = () => {
  const { authStore } = useStores();
  const { isAuthenticated, user } = authStore;

  useEffect(() => {
    if (isAuthenticated) {
      console.log('initializing');
      ReactGA.initialize(TRACKING_ID, {
        testMode: true,
        gaOptions: {
          userId: String(user?.id),
        },
      });
    }
  }, [isAuthenticated]);
};

I set testMode to true in order to have the logs (like the react-ga debug flag). Also, I'm using the G-XXX type of tracking id but I cant see anything updating in the GA dashboard. Am I missing something?

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.

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?

is this library dead?

Can anyone confirm if this library is still alive? For the comments that I'm reading here make me think that this doesn't work very well?

No event category or label values

I'm setting event category and label values for each of my events, but cannot see any data in my GA4. In every report, it says (not set) - any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.