diff --git a/package-lock.json b/package-lock.json index 8cc39e9..82b5002 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "@govtechsg/open-attestation": "^6.10.0-beta.4", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-ga4": "^2.1.0", "react-router-dom": "^6.6.1" }, "devDependencies": { @@ -17772,6 +17773,11 @@ "integrity": "sha512-/6UZ2qgEyH2aqzYZgQPxEnz33NJ2gNsnHA2o5+o4wW9bLM/JYQitNP9xPhsXwC08hMMovfGe/8retsdDsczPRg==", "dev": true }, + "node_modules/react-ga4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/react-ga4/-/react-ga4-2.1.0.tgz", + "integrity": "sha512-ZKS7PGNFqqMd3PJ6+C2Jtz/o1iU9ggiy8Y8nUeksgVuvNISbmrQtJiZNvC/TjDsqD0QlU5Wkgs7i+w9+OjHhhQ==" + }, "node_modules/react-is": { "version": "17.0.2", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", diff --git a/package.json b/package.json index 3a67391..d2ba9c7 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "@govtechsg/open-attestation": "^6.10.0-beta.4", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-ga4": "^2.1.0", "react-router-dom": "^6.6.1" }, "devDependencies": { diff --git a/src/app.tsx b/src/app.tsx index 0e63eb3..8f8aade 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -1,8 +1,12 @@ import React from "react"; import { Router } from "./router"; +import { useGoogleAnalytics } from "./utils/google-analytics"; -export const App: React.FunctionComponent = () => ( -
- -
-); +export const App: React.FunctionComponent = () => { + useGoogleAnalytics(); + return ( +
+ +
+ ); +}; diff --git a/src/utils/google-analytics.ts b/src/utils/google-analytics.ts new file mode 100644 index 0000000..5509a83 --- /dev/null +++ b/src/utils/google-analytics.ts @@ -0,0 +1,20 @@ +import { useEffect } from "react"; +import ReactGA from "react-ga4"; + +/** + * Initialise Google Analytics 4 only once (if GTAG_ID is provided) + * + * The ReactGA.send("pageview") is explicitly called afterwards because + * the pageview event is not automatically triggered on first initialisation + * but will be automatically triggered by the GA script on subsequent page views. + */ +export const useGoogleAnalytics = (): void => { + useEffect(() => { + try { + ReactGA.initialize("G-GXV2BSGK4K"); + ReactGA.send("pageview"); + } catch (e) { + console.error(e); + } + }, []); +};