How to set up Google Analytics 4 for React-Router?
You can call gtag
directly. Just put the global site tag code in your index.html <head>
.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
I was facing the same issue today and ended up pulling out the react-ga package and going this route. I saved the withTracker.js piece from the react-ga demo code and modified it like below.
export default function withTracker(WrappedComponent, options = {}) {
const trackPage = (page) => {
window.gtag('send', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname
});
};
...