Skip to content

Instantly share code, notes, and snippets.

@secretorange
Created August 20, 2022 05:37
Show Gist options
  • Save secretorange/c3de5553ab57c70e278a4274bee993cd to your computer and use it in GitHub Desktop.
Save secretorange/c3de5553ab57c70e278a4274bee993cd to your computer and use it in GitHub Desktop.
Simple React GoogleAnalytics tracker. No dependencies.
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
interface IProps {
key: string;
}
export function GoogleAnalytics({ key }: IProps) {
const location = useLocation();
// We don't want to track the first page load as it's allready tracked in the script (_gaq.push(['_trackPageview']))
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (loaded && (window as any)._gaq) {
(window as any)._gaq.push(["_trackPageview", location.pathname]);
}
if(!loaded){
setLoaded(true);
}
}, [location]);
const SCRIPT = `
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '${key}']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
`;
return (
<script
dangerouslySetInnerHTML={{
__html: SCRIPT,
}}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment