Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
)
like image 551
coconutisGood'3 Avatar asked Jun 27 '18 21:06

coconutisGood'3


People also ask

Where do I paste GTAG js?

To install the Google tag, copy the following code and paste it immediately after the <head> tag on every page of your site. Replace GA_TRACKING_ID with the ID of the Google Analytics property to which you want to send data. You need only one snippet per page.


1 Answers

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

like image 58
Darryl RN Avatar answered Sep 20 '22 05:09

Darryl RN