Skip to content

Latest commit

 

History

History
46 lines (33 loc) · 1.17 KB

using_ga4.md

File metadata and controls

46 lines (33 loc) · 1.17 KB

How to add GA4 into React

First we need to install the following packages

These two will allow us to implement Google Analytics into our React App.

Inside a utils / modules directory within your src add the following:

// ga.js

import ReactGA from 'react-ga4'

// initialize google analytics
ReactGA.initialize('G-XXX')

// custom pageview with the location from react router
export const pageView = path => {
  return ReactGA.send({hitType: 'pageview', page: path})
}

// custom event with label being an optional parameter
export const customEvent = (category, action, label = '') => {
  return ReactGA.event({
    category: category,
    action: action,
    label: label,
  })
}

This allows us to import a simple PageView function and also a customEvent function, inside anywhere in our app. We then call those functions like so...

import {useLocation} from 'react-router-dom'
import {pageView} from './utils/ga'

useEffect(() => {
    let location = useLocation()
    pageView(location.pathname)
  }, [])