Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Created May 2, 2022 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/e7662195827d6befd5308cb7516c3f89 to your computer and use it in GitHub Desktop.
Save erkobridee/e7662195827d6befd5308cb7516c3f89 to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { useRouter } from 'next/router';
//----------------------------------------------------------------------------//
const isBrowser = window !== undefined;
type Gtag = (...args: any[]) => void;
export interface IGoogleAnalyticsPageView {
page_title?: string;
page_location?: string;
page_path: URL | string;
}
//----------------------------------------------------------------------------//
export const gtag: Gtag = (...args) => {
if (!isBrowser || !window['gtag']) return;
window['gtag'](args[0], args[1], args[3]);
};
export const event = (action: string, values: any) => {
gtag('event', action, values);
};
export const pageView = (param: IGoogleAnalyticsPageView) => {
event(
'page_view',
Object.entries(param)
.filter((entry) => !!entry[1])
.reduce((acc, entry) => {
acc[entry[0]] = entry[1];
return acc;
}, {})
);
};
//----------------------------------------------------------------------------//
const EVENT_NAME = 'routeChangeComplete';
export const GALogRouteChange: React.FunctionComponent = () => {
const router = useRouter();
React.useEffect(() => {
const handleRouteChange = (url: URL) => {
pageView({ page_path: url });
};
router.events.on(EVENT_NAME, handleRouteChange);
return () => {
router.events.off(EVENT_NAME, handleRouteChange);
};
}, [router.events]);
return null;
};
export default GALogRouteChange;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment