pricerunner / react-ga4 Goto Github PK
View Code? Open in Web Editor NEWReact Google Analytics 4
Home Page: https://www.npmjs.com/package/react-ga4
React Google Analytics 4
Home Page: https://www.npmjs.com/package/react-ga4
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?
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
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
please help
thanks
When a new pageview event is executed in the code, it takes almost 5 seconds for the actual network call to occur.
Not possible to anonymizeIp and location anymore with react-ga4.
ReactGA.set({ anonymizeIp: true })
ReactGA.set({ location: 'Anonymized' })
Doesn't really work with anonymizing
@codler how to track OutboundLink with target: '_self'
GA event get cancelled if user redirect on same tab .
need help .thanks in advance.
Is it possible to set a custom user id?
It would be great to have a little more information in the Readme.
Thanks!
Hi, first of all, thanks for the support and dedication ๐๐ป
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",
}
});
Does anyone know which is the main problem with this initialization?
Thank you all.
Is there a way to enforce nonce for CSP support?
There are several problems with typings
Somewhere you put any
like in this example
Line 46 in f31ed50
Line 479 in f31ed50
any
anyway.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
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' }
} );
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')
.
We are using AdWords, DS3/Floodlight, GA4 and UA all from the gtag code.
In our non-react code, we use the send_to
property in the event as described here: https://support.google.com/analytics/answer/10271001?hl=en#zippy=%2Cin-this-article
This helps us to send the correct category/event/etc to the correct properties as needed.
I'm not seeing a property in this package to specifically do that.
ReactJS erro, need @types/react-ga4.
Hi there, I am implementing this library but am curious why these lines exists:
Lines 473 to 488 in 0e2e3a6
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 initialize, gives options to make the titleCase boolean false. Could such an option be added in react-ga4 as well?
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",
});
hi, is it possible to do something like this: https://developers.google.com/analytics/devguides/collection/ga4/ecommerce?client_type=gtm#view_item_details using this package?
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.
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
Could you add a function, boolean or switch to turn off ReactGA if used locally for dev purposes?
Just adding a reference to this comment, related to Multiple Tracker Support:
react-ga/react-ga#493 (comment)
If / when this implemented, this would be amazing
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.
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
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');
};
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?
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
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
I am trying to disable the default page_view event, but I don't have clear idea about where we need to put this "send_page_view: false".
Please help me to fix the issue
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}</>;
}
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')
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.
in the console.log, it is importing both ReactGAImplementation and default so it can only be initialize through ReactGA.default.initialize().
Is this intended because the usage tutorial is not stated like that
With react-ga
we used ReactGA.outboundLink
function.
Looks like it's not supported for react-ga4
More info can be found here https://github.com/react-ga/react-ga#reactgaoutboundlinkargs-hitcallback
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;
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:
Line 193 in 6822d0f
Since ga4, events can be sent with custom parameters.
The current implementation of ReactGA does not match gtag.
Something like this would match gtag :
ReactGA.event('myEvent', { my_param_1: 'my_value_1' })
https://developers.google.com/tag-platform/gtagjs/reference#event
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
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' },
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!
I need to use both GA4 and UA.. Not sure if I have to use react-ga and react-ga4 all together or I can simply just use this one for both...
Can you add LICENSE file to a repository?
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?
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.
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?
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?
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?
ReactGA.plugin.execute('ecommerce', 'addItem', 'purchase', {
id: author.id,
revenue: 100,
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.