Where should I put the Google Analytics 4 custom event tracking code in a React app?

104 views Asked by At

I am trying to track custom events in Google Analytics 4 in a React app. I do not want to use a library like react-ga4 because the docs lack a lot of information. So what I am doing is following the developer google guide to implement GA4 tracking using code snippets. for example, this code goes in the public/index.html in th head tag:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

But when I need to track custom events google developer tells me I need to use snippets like this:

dataLayer.push({
  'event' : 'CTA_download _file',
  'evtCat' : ‘$filetype’, 
  'evtAct' : ‘download’, 
  'evtLab' : ‘$fileName’
});

But how to insert this code in a react component since dataLayer is not declared and it is only in public/index.html?

0

There are 0 answers