From 8369c20714983efc3a9c1a65d27f2f8aa37a9bc3 Mon Sep 17 00:00:00 2001 From: Dave Horton Date: Sun, 7 May 2023 09:30:05 -0400 Subject: [PATCH] handle page views for google tag manager --- pages/_app.js | 29 +++++++++++++++++++++++------ src/components/hooks.js | 23 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/pages/_app.js b/pages/_app.js index 96ef996..1ceadcb 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -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 -} \ No newline at end of file + + usePageViewTracking(gtagId); + + return ; +} + + + + diff --git a/src/components/hooks.js b/src/components/hooks.js index cdfff2a..7c150d0 100644 --- a/src/components/hooks.js +++ b/src/components/hooks.js @@ -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();