Tracking
Tracking refers to a users action that is captured on the client side and pushed to Google Tag Manager (GTM).
They are built up in an array that is stored on the window object. This example will explain how to create and push to the dataLayer stored in the browser window.
We are going to be using react-tracking as a helper tool, specifically the hooks implementation.
Install
npm install --save react-tracking; npm i --save-dev @types/react-tracking
or
yarn add react-tracking; yarn add --dev @types/react-tracking
Configure
Create a custom _app.tsx file - more instructions here.
Include the two script tags below swapping out GA_ID for the correct value, or even better, storing it as an environment variable.
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
Usage
When create a new page include the useTracking hook to initialise a new tracking page.
import { useTracking } from 'react-tracking';
const Page = () => {
const { Track } = useTracking({ page: 'My New Page' });
return (
<div>
<h1>New Page<p>
</div>
)
}
For each user event we can then attach specific actions, event names or any other data without re-declaring the page name again.
import { useTracking } from 'react-tracking';
const Page = () => {
const { Track, trackEvent } = useTracking({ page: 'My New Page' });
// Alternatively it can be scoped to a component
// const { Track, trackEvent } = useTracking({ component: 'My New Component' });
const handleClick = () => trackEvent({ action: 'button clicked' })
return (
<div>
<h1>New Page<p>
<button onClick={handleClick}>My button</button>
</div>
)
}
Things to note
Never do an inline track function
// bad
<button onClick={() => trackEvent}>My Button</button>
// good
const handleClick = () => trackEvent({...})
<button onClick={() => trackEvent({...})}>My Button</button>