Created
August 20, 2022 05:37
-
-
Save secretorange/c3de5553ab57c70e278a4274bee993cd to your computer and use it in GitHub Desktop.
Simple React GoogleAnalytics tracker. No dependencies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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