Replies: 3 comments 3 replies
-
|
This is how I currently do it const router = getRouter(queryClient);
const Root = (
<StrictMode>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</StrictMode>
);
root.render(Root);
router.history.subscribe(() => {
const url = router.history.location.href
// your Favorite Analytics code here
}); |
Beta Was this translation helpful? Give feedback.
-
|
Here is my solution for hash routing. Configure Google Analytics to turn off sending page views automatically, and instead send the first page view manually:
|
Beta Was this translation helpful? Give feedback.
-
|
I ran into the kluge of integrating Google Analytics with TanStack Router, so I created this: https://github.com/bhouston/tanstack-router-ga4 You can integrate it into your TanStack Router / Start project like this: import { GoogleAnalytics } from "tanstack-router-ga4";
// In your root document — automatic page_view on each route change
function RootDocument({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<GoogleAnalytics measurementId="G-XXXXXXXXXX" />
{children}
<Scripts />
</body>
</html>
);
}It will track your pages automatically. If you want more, you can use the useGoogleAnalytics() hook and then send custom events: // In any component — track custom events
function SignupForm() {
const ga = useGoogleAnalytics();
const handleSubmit = () => {
const user = await registerUser({ email: "ada@example.com", password: "secure-password" });
// associate user id with session
ga.set({
user_id: user.id,
user_properties: {
email: user.email,
username: user.username,
},
});
// send standard GA event for signups
ga.event("sign_up", { method: "email" });
};
return <button onClick={handleSubmit}>Sign up</button>;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'd like to use GA to track page viewed.
Beta Was this translation helpful? Give feedback.
All reactions