ScottSpence.com

Scott's Digital Garden.

🤫This is a private post👀

Track Custom Events With Google Analytics

Do you use Google Analytics (GA) for any of your sites?

I’ve used it in the past and it gives quite good information about

Want to track what users of your site are clicking and navigating to?

Let’s talk about Google Analytics, what is it used for

Tracking Events

Privacy Policy

Ambulance Chasers

We’re going to use the React context API

1import React, { useContext, useEffect } from 'react'
2
3const AnalyticsContext = React.createContext({})
4
5export const AnalyticsProvider = ({ children }) => {
6 useEffect(() => {
7 if (typeof window.ga === 'undefined') {
8 window.ga = (x, y) => {
9 console.log(`I'm a fake GA`, x, y)
10 }
11 }
12 }, [])
13
14 const events = {
15 logButtonPress: e => {
16 window.ga('send', {
17 hitType: 'event',
18 eventCategory: 'buttonPress',
19 eventAction: 'click',
20 eventLabel: e.target.innerText,
21 })
22 },
23 logSocial: socialMediaPlatform => {
24 window.ga('send', {
25 hitType: 'event',
26 eventCategory: 'socialShareClicks',
27 eventAction: 'click',
28 eventLabel: socialMediaPlatform,
29 })
30 },
31 logNavigation: navItem => {
32 window.ga('send', {
33 hitType: 'event',
34 eventCategory: 'navigationClicks',
35 eventAction: 'click',
36 eventLabel: navItem,
37 })
38 },
39 }
40 return (
41 <AnalyticsContext.Provider value={events}>
42 {children}
43 </AnalyticsContext.Provider>
44 )
45}
46
47export const useAnalytics = () => {
48 return useContext(AnalyticsContext)
49}

As high up the component tree add the provider.

1import { AnalyticsProvider } from '../components/GAEventTracking'

Then use in the areas you Want

1export const ButtonComponent = props => {
2 const analytics = useAnalytics()
3 return (
4 <button onClick={analytics.logButtonPress} {...props}>
5 {props.children}
6 </button>
7 )
8}

Back to Top