Skip to content

Instantly share code, notes, and snippets.

@jbutko
Created December 22, 2020 15:58
Show Gist options
  • Save jbutko/ac098733fcb05cb8a44ebd88c856e889 to your computer and use it in GitHub Desktop.
Save jbutko/ac098733fcb05cb8a44ebd88c856e889 to your computer and use it in GitHub Desktop.
Google Analytics: React util (react-ga)
import ReactGA, { InitializeOptions, EventArgs } from 'react-ga';
const gaOptsDefault = {
debug: true,
siteSpeedSampleRate: 100,
};
export const GA_ID = 'G-XXXXXXXXXXX';
export const GA_EVENTS = {
page_view: 'page_view',
};
/**
* Initialize GA tracking
* example:
*/
export const gaInitialize = (trackingId: string = GA_ID, opts: InitializeOptions = {}) =>
ReactGA.initialize(trackingId, { ...gaOptsDefault, ...opts });
/**
* Send GA Event
* example:
* {
* category: 'Promotion',
* action: 'Displayed Promotional Widget',
* label: 'Homepage Thing',
* value: 3,
* transport: 'xhr',
* nonInteraction: true
* }
*/
export const gaSendEvent = (
category: EventArgs['category'],
action: EventArgs['action'],
value?: EventArgs['value'],
transport?: EventArgs['transport'],
nonInteraction?: EventArgs['nonInteraction']
): void =>
ReactGA.event({
category,
action,
value,
transport,
nonInteraction,
});
export const gaPageView = () => ReactGA.pageview(window.location.pathname + window.location.search);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment