I'm trying to set up Google Analytics 4 on my react site. Previously I used react-ga, but this library doesn't support Google Analytics 4 yet. I pasted the GA4 tag directly into the index.html file without an external library. What additional code do I need to add to get GA4 to work with react router?
Thanks in advance!
This post will show you how to use Google Analytics with React Router V4 in three easy steps. While you can’t just paste in your embed code and be done with it, it’s still pretty easy to use Google Analytics in a single page application. This is how I do it: Add react-gato your project with npm or yarn: yarn add react-ga
How to Setup and Add Google Analytics to your React App. 1 Step 1. Create an Account. Go to analytics.google.com. 2 Step 2. Create a Property. 3 Step 3. Install Dependencies. 4 Step 4. Setup Analytics Inside Project. 5 Step 5. Record Custom Events. More items
It is an undeniable fact that React and Google Analytics are one of the most popular tools and libraries among the web-analyst community. Google Analytics is the most widely used web analysis tool, which helps you easily track and retarget your users.
Simply add the component within your router (I believe ideally after any routes that would be matched and any Switch components, because the analytics function should not be priority over your site rendering):
You can call gtag
directly. Just put the global site tag code in your index.html <head>
.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
I was facing the same issue today and ended up pulling out the react-ga package and going this route. I saved the withTracker.js piece from the react-ga demo code and modified it like below.
export default function withTracker(WrappedComponent, options = {}) {
const trackPage = (page) => {
window.gtag('send', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname
});
};
...
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