Skip Navigation

Scott Spence

Track Custom Events With Google Analytics

2 min read
Hey! Thanks for stopping by! Just a word of warning, this post is about 4 years old, wow! If there's technical information in here it's more than likely out of date.

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

import React, { useContext, useEffect } from 'react'

const AnalyticsContext = React.createContext({})

export const AnalyticsProvider = ({ children }) => {
  useEffect(() => {
    if (typeof window.ga === 'undefined') {
      window.ga = (x, y) => {
        console.log(`I'm a fake GA`, x, y)
      }
    }
  }, [])

  const events = {
    logButtonPress: e => {
      window.ga('send', {
        hitType: 'event',
        eventCategory: 'buttonPress',
        eventAction: 'click',
        eventLabel: e.target.innerText,
      })
    },
    logSocial: socialMediaPlatform => {
      window.ga('send', {
        hitType: 'event',
        eventCategory: 'socialShareClicks',
        eventAction: 'click',
        eventLabel: socialMediaPlatform,
      })
    },
    logNavigation: navItem => {
      window.ga('send', {
        hitType: 'event',
        eventCategory: 'navigationClicks',
        eventAction: 'click',
        eventLabel: navItem,
      })
    },
  }
  return (
    <AnalyticsContext.Provider value={events}>
      {children}
    </AnalyticsContext.Provider>
  )
}

export const useAnalytics = () => {
  return useContext(AnalyticsContext)
}

As high up the component tree add the provider.

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

Then use in the areas you Want

export const ButtonComponent = props => {
  const analytics = useAnalytics()
  return (
    <button onClick={analytics.logButtonPress} {...props}>
      {props.children}
    </button>
  )
}

There's a reactions leaderboard you can check out too.

Analytics Information

Monthly analytics for this post

Views This Month
4
Sep 1, 2023 - Sep 28, 2023
Visitors This Month
2
Sep 1, 2023 - Sep 28, 2023
Entries This Month
3
Sep 1, 2023 - Sep 28, 2023

Yearly analytics for this post

Views This Year
40
Jan 1, 2023 - Sep 28, 2023
Visitors This Year
22
Jan 1, 2023 - Sep 28, 2023
Entries This Year
24
Jan 1, 2023 - Sep 28, 2023

Copyright © 2017 - 2023 - All rights reserved Scott Spence