Skip to content

Commit

Permalink
feat: google analytics (#66)
Browse files Browse the repository at this point in the history
* chore: npm i react-ga4

* feat: add google analytics via react-ga4

https://github.com/codler/react-ga4?tab=readme-ov-file#usage
  • Loading branch information
HJunyuan authored Aug 5, 2024
1 parent 110f912 commit c39c46c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 5 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
14 changes: 9 additions & 5 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import React from "react";
import { Router } from "./router";
import { useGoogleAnalytics } from "./utils/google-analytics";

export const App: React.FunctionComponent = () => (
<div className="flex flex-col min-h-screen">
<Router />
</div>
);
export const App: React.FunctionComponent = () => {
useGoogleAnalytics();
return (
<div className="flex flex-col min-h-screen">
<Router />
</div>
);
};
20 changes: 20 additions & 0 deletions src/utils/google-analytics.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}, []);
};

0 comments on commit c39c46c

Please sign in to comment.