Skip to content

Commit 3de9f1b

Browse files
committed
feat: integrate google analytics to track page views across all react routes
1 parent 7bc8fc0 commit 3de9f1b

File tree

4 files changed

+39
-2
lines changed

4 files changed

+39
-2
lines changed

public/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@
125125
}
126126
gtag("js", new Date());
127127

128-
gtag("config", "G-F0BKEF4Y2R");
128+
gtag("config", "G-F0BKEF4Y2R", { send_page_view: false });
129129
</script>
130130
</body>
131131
</html>

src/App.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@ import { GlobalStyles } from "@mui/material";
22
import { ThemeProvider } from "@mui/material/styles";
33
import Routes from "components/Routes";
44
import theme from "design/theme";
5+
import { useGAPageviews } from "hooks/useGAPageviews";
56
import { BrowserRouter } from "react-router-dom";
67

8+
function GATracker() {
9+
useGAPageviews();
10+
return null;
11+
}
12+
713
const App = () => {
814
return (
915
<ThemeProvider theme={theme}>
@@ -15,6 +21,7 @@ const App = () => {
1521
}}
1622
/>
1723
<BrowserRouter basename={process.env.PUBLIC_URL}>
24+
<GATracker />
1825
<Routes />
1926
</BrowserRouter>
2027
</ThemeProvider>

src/components/SearchPage/SubjectCard.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,12 @@ const SubjectCard: React.FC<SubjectCardProps> = ({
4242

4343
if (genderCode) {
4444
if (genderCode === "000F") genderDisplay = "Female";
45-
else if (genderCode === "000M") genderDisplay = "Male";
45+
else if (
46+
genderCode === "000M" ||
47+
genderCode === ",M,F" ||
48+
genderCode === ",M,M"
49+
)
50+
genderDisplay = "Male";
4651
}
4752

4853
// cover age string to readable format

src/hooks/useGAPageviews.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { useEffect } from "react";
2+
import { useLocation } from "react-router-dom";
3+
4+
declare global {
5+
interface Window {
6+
gtag?: (...args: any[]) => void;
7+
}
8+
}
9+
10+
export function useGAPageviews(measurementId = "G-F0BKEF4Y2R") {
11+
const location = useLocation();
12+
13+
useEffect(() => {
14+
// guard for dev or if gtag not yet loaded
15+
if (typeof window.gtag !== "function") return;
16+
17+
const path = location.pathname + location.search + location.hash;
18+
19+
// GA4 recommended SPA approach: call config on each route change
20+
window.gtag("config", measurementId, {
21+
page_path: path,
22+
page_title: document.title,
23+
});
24+
}, [location, measurementId]);
25+
}

0 commit comments

Comments
 (0)