how to add gtag.js to react.js/next.js index.js?

coconutisGood'3 picture coconutisGood'3 · Jun 27, 2018 · Viewed 11.1k times · Source

I am sorry for this noob question, I just start to use a next.js template form https://github.com/zeit/next.js/tree/canary/examples/hello-world/pages Normally I would just add gtag.js to index.html but for this next.js there is only index.js. The question is how I can include this? I had tried to make gtag as a component and try to import it and also include the script as it is inside render function of index.js but so far it is not working! please help me!

Gtag:

 <script async src="https://www.googletagmanager.com/gtag/js? 
   id=GA_TRACKING_ID"></script>
    <script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_TRACKING_ID');
</script>

index.js:

import Link from 'next/link'
export default () => (
  <div>Hello World. <Link href='/about'><a>About</a></Link></div>
)

Answer

Darryl RN picture Darryl RN · Oct 17, 2018

You can add the gtag func as lib like this:

export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>'

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
  window.gtag('config', GA_TRACKING_ID, {
    page_location: url
  })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value
  })
}

For complete example of how to add google analytics in NextJS, you can take a look here