I'm trying to add Google Analytics GA4 to a React Application,
index.html
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-xxxxxxxL', {send_page_view: false});
</script>
Except that this does not disable the default page_view event.
I would like to disable the default request so I manually send page_view events. they are some pages where the title is not set unlike a saga returns, for example: Project: . the default event sets to undefined, which make sense because data is not loaded yet.
So I how can I achieve this?
react-ga does not work with GA-4.
This means that when you create a new GA4 property and data stream, basic user interactions such as outbound link clicks, scrolls, file downloads, video engagement, and site search are automatically tracked.
If your Universal Analytics property is implemented with gtag. js, you can dual tag for your Google Analytics 4 property in one of the following ways: Use the GA4 Setup Assistant and select the option to "Enable data collection using your existing tags" (This option uses a feature called connected site tags)
Try toggling the option to automatically track history events as page cries OFF from the Enhanced Measurement settings in GA4 admin (Web Stream settings).
Many SPA sites have an initial pushState/replaceState in place for state management purposes (or for other reasons), which would cause a page_view to be tracked of that Enhanced Measurement option is toggled on.
Do you disable gtag on every webpage?
As the docs say:
The send_page_view setting does not persist across pages. This setting must be repeated on every page of your website where you want to disable automatic pageviews.
I ran into the same problem, my initial idea was that sincs the default index.html
loads as a framing for the react app, I can disable page_view
events on all pages just by adding the snippet here. But this was not the case for me.
I ended up programmatically removing the gtag events from dataLayer
on the componentDidMount
of App.tsx with the ts equivalent of a pseudo snippet like this (I dont have the exact code on me right now):
window.dataLayer = window.dataLayer.filter(element => element['event'] && !(element['event'] === 'gtm.load' || element['event'] === 'gtm.dom'));
This is as crazy as it looks: we remove the tags responsible for page hits right from the data buffer. This seems to work but it not only is a major hack, but looks ugly in my opinion, so any better non-lib way for this is much appreciated on my side!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With