1- import Head from 'next/head' ;
21import { useRouter } from 'next/router' ;
2+ import Script from 'next/script' ;
33import { createContext , useContext , useEffect } from 'react' ;
44
55type Context = Readonly < {
66 event : ( payload : GoogleAnalyticsEventPayload ) => void ;
77} > ;
88
9+ const MEASUREMENT_ID = 'G-DBLZDQ2ZZN' ;
10+
911export const GoogleAnalyticsContext = createContext < Context > ( {
1012 event,
1113} ) ;
1214
1315// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
14- function pageview ( measurementID : string , url : string ) {
16+ function pageview ( url : string ) {
1517 // Don't log analytics during development.
1618 if ( process . env . NODE_ENV === 'development' ) {
1719 return ;
@@ -21,7 +23,6 @@ function pageview(measurementID: string, url: string) {
2123 page_location : window . location . href ,
2224 page_path : url ,
2325 page_title : document . title ,
24- send_to : measurementID ,
2526 } ) ;
2627}
2728
@@ -53,49 +54,46 @@ export function event({
5354
5455type Props = Readonly < {
5556 children : React . ReactNode ;
56- measurementID : string ;
5757} > ;
5858
5959export function useGoogleAnalytics ( ) {
6060 return useContext ( GoogleAnalyticsContext ) ;
6161}
6262
63- export default function GoogleAnalytics ( { children, measurementID } : Props ) {
63+ export default function GoogleAnalytics ( { children } : Props ) {
6464 const router = useRouter ( ) ;
6565 useEffect ( ( ) => {
6666 function handleRouteChange ( url : string ) {
67- pageview ( measurementID , url ) ;
67+ pageview ( url ) ;
6868 }
6969
7070 router . events . on ( 'routeChangeComplete' , handleRouteChange ) ;
7171 return ( ) => {
7272 router . events . off ( 'routeChangeComplete' , handleRouteChange ) ;
7373 } ;
74- } , [ router . events , measurementID ] ) ;
74+ } , [ router . events , ] ) ;
7575
7676 return (
7777 < GoogleAnalyticsContext . Provider value = { { event } } >
7878 { children }
79- < Head >
80- { /* TODO(yangshun): Change back to next/script in future. */ }
81- { /* Global Site Tag (gtag.js) - Google Analytics */ }
82- < script
83- async = { true }
84- src = { `https://www.googletagmanager.com/gtag/js?id=${ measurementID } ` }
85- />
86- < script
87- dangerouslySetInnerHTML = { {
88- __html : `
79+ { /* Global Site Tag (gtag.js) - Google Analytics */ }
80+ < Script
81+ async = { true }
82+ src = { `https://www.googletagmanager.com/gtag/js?id=${ MEASUREMENT_ID } ` }
83+ />
84+ < Script
85+ dangerouslySetInnerHTML = { {
86+ __html : `
8987 window.dataLayer = window.dataLayer || [];
9088 window.gtag = function(){dataLayer.push(arguments);}
9189 gtag('js', new Date());
92- gtag('config', '${ measurementID } ', {
90+ gtag('config', '${ MEASUREMENT_ID } ', {
9391 page_path: window.location.pathname,
9492 });
9593 ` ,
96- } }
97- />
98- </ Head >
94+ } }
95+ id = "google-analytics"
96+ / >
9997 </ GoogleAnalyticsContext . Provider >
10098 ) ;
10199}
0 commit comments