alinemorelli / react-gtm

React Google Tag Manager
MIT License
658 stars 140 forks source link

Sending Specific Page Views to GA4 #105

Open jordanlambrecht opened 2 years ago

jordanlambrecht commented 2 years ago

I'm a little confused on the steps for this. I have the following on my _app.tsx:

  const tagManagerArgs = {
    gtmId: 'GTM-REDACTED',
    events: {
      sendUserInfo: 'userInfo',
    },
  }
  TagManager.initialize(tagManagerArgs)

And the following on a component called JobPost:

  const tagManagerArgs = {
    dataLayer: {
      page: `${frontMatter.title}`,
    },
    dataLayerName: 'PageDataLayer',
  }
  TagManager.dataLayer(tagManagerArgs)

The goal is to track page views for job postings as a datalayer so I can easily look at the most popular ones in GA4. How do I move this data into Tag Manager and then over to GA?

kodiekenta commented 2 years ago

what npm version did you use to install the package

gubikmic commented 1 year ago

This works for me

export default function SomePage() {
  window.dataLayer.push({
    event: 'pageview',
    page: {
      url: document.location.origin + document.location.pathname + document.location.search,
      title: 'SomePage',
    },
  })

  return (
    <>
      ...
    </>
  )
}

⚠️ In React strict mode (default for CRA) components render twice, so in DEV this will lead to two events firing