Skip to main content

One post tagged with "ga4"

View All Tags

ยท 2 min read
Ziinc

Wouter is amazingly lightweight, and if it can do much work in a tiny package, so can you!

Here is my tried and tested way to track routes in a React app using Wouter as the main browser router:

Installationโ€‹

This guide assumes that you already have a working router set up with wouter already installed. This is for v3 of wouter.

We'll use react-ga4 package, because popping npm package pills is more fun than hand-rolling it.

npm i react-ga4

In the App.tsx, initialize the React GA4 script:

import ReactGA from "react-ga4";

ReactGA.initialize([
{
trackingId: "G-mytrackingnum",
gaOptions: { anonymizeIp: true },
},
]);

Create a <TrackedRoute /> Componentโ€‹

import { Route, RouteProps useLocation, useRoute } from "wouter";
const TrackedRoute = (props: RouteProps) => {
const [location, _setLocation] = useLocation();
const [match] = useRoute(props.path as string);
useEffect(() => {
if (match) {
ReactGA.send({
hitType: "pageview",
page: props.path,
title: document.title,
});
}
}, [location]);

return <Route {...props} />;
};

In this example, we trigger the effect every time the browser location changes. We then check if the route matches, and if it does, we will fire off the ReactGA pageview event.

Add it to the <Router> componentโ€‹

import { Router } from "wouter";

<Router base={import.meta.env.BASE_URL}>
<TrackedRoute path="/test/:testing">some test page</TrackedRoute>
<TrackedRoute path="/">some app code</TrackedRoute>
</Router>;

And now, if we navigate to /test/123, we will see that the pageview of /test/:testing will get logged.

Note that this example only focuses on the path route that is matched, and not the actual location. This is app routes are not really the same as public content routes and the actual resource IDs are irrelevant to the web analytics.