Skip to content

Instantly share code, notes, and snippets.

@trezy
Last active October 10, 2019 02:54
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trezy/e26cb7feb2349f585d2daf449411d0a4 to your computer and use it in GitHub Desktop.
Save trezy/e26cb7feb2349f585d2daf449411d0a4 to your computer and use it in GitHub Desktop.
import NextHead from 'next/head'
import React from 'react'
import ReactGA from 'react-ga'
import Router from 'next/router'
/*****************************************************************************\
Make sure to insert your tracking ID. Otherwise nothing's gonna happen! 😁
\*****************************************************************************/
const gaTrackingId = '[GOOGLE ANALYTICS TRACKING ID GOES HERE]'
/*****************************************************************************\
We'll set the `onRouteChangeComplete` method to a function that sends our
pageview to GA. I'm using ReactGA for this, but you can also do it manually
with the `window.gtag` method.
\*****************************************************************************/
Router.onRouteChangeComplete = () => {
ReactGA.initialize(gaTrackingId)
ReactGA.pageview(window.location.pathname)
}
export default class extends React.Component {
render () {
return (
<!--
Using the `<NextHead />` component allows us to inject stuff into the
`<head />` element that Next generates for us.
-->
<NextHead>
<!--
Import the `gtag` script
-->
<script async src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`} />
<!--
This ensures that the first page view gets sent to GA. All subsequent
page views will be handled by the `Router.onRouteChangeComplete`
method we set up above.
-->
<script dangerouslySetInnerHTML={{ __html: `
window.dataLayer = window.dataLayer || []
function gtag(){
dataLayer.push(arguments)
}
gtag('js', new Date())
gtag('config', '${gaTrackingId}')
`}} />
</NextHead>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment