handle page views for google tag manager

This commit is contained in:
Dave Horton
2023-05-07 09:30:05 -04:00
parent 5a98730474
commit 8369c20714
2 changed files with 46 additions and 6 deletions

View File

@@ -1,12 +1,29 @@
import '../src/styles/global.scss';
import { useEffect } from 'react'
import TagManager from 'react-gtm-module'
import { useEffect } from 'react';
import TagManager from 'react-gtm-module';
import { usePageViewTracking } from '../src/components/hooks.js';
const gtmId = 'G-7J55WH6BVM';
const gtagId = 'G-7J55WH6BVM';
export default function App({ Component, pageProps }) {
useEffect(() => {
TagManager.initialize({ gtmId })
TagManager.initialize({
gtmId: gtagId,
dataLayer: {
gtag_id: gtagId,
config: {
[gtagId]: { groups: 'default' },
},
},
});
}, []);
return <Component {...pageProps} />
usePageViewTracking(gtagId);
return <Component {...pageProps} />;
}

View File

@@ -4,6 +4,29 @@ import { useState, useEffect, useCallback } from 'react';
import { rSlash } from './utils';
export function usePageViewTracking(gtagId) {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url) => {
window.dataLayer.push({
event: 'page_view',
gtag_id: gtagId,
config: {
[gtagId]: {
page_path: url,
groups: 'default',
},
},
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events, gtagId]);
}
export function useActiveNavi() {
const router = useRouter();