Escape the analytics code with dangerouslySetInnerHTML
First you have of course to share the header code to all pages, e.g. as asked at: React js do common header
Then, this Next.js answer https://mcmap.net/q/79813/-what-39-s-the-proper-value-for-a-checked-attribute-of-an-html-checkbox gives a good working code that should also work outside of Next.js. It escapes the analytics code with dangerouslySetInnerHTML
:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-47867706-3"></script>
<script
dangerouslySetInnerHTML={{
__html: `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-47867706-3', { page_path: window.location.pathname });
`,
}}
/>
where you should replace UA-47867706-3
with your own code.
This code is exactly the code that Google gives, but with the following modification: we added the:
{ page_path: window.location.pathname }
to gtag('config'
for it to be able to get the visited path, since this is a JavaScript SPA.
This generates the desired output on the browser:
<script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-47867706-3"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-47867706-3', { page_path: window.location.pathname });
</script>
The only other divergence from the exact code given by Google is the async=""
vs async
, but both of those are equivalent in HTML since it is a boolean attribute, see also: What's the proper value for a checked attribute of an HTML checkbox?
Escaping with dangerouslySetInnerHTML
is necessary because otherwise React interprets the code inside script
a JSX and that fails with:
Syntax error: Unexpected token, expected "}"
21 | <script>
22 | window.dataLayer = window.dataLayer || [];
> 23 | function gtag(){dataLayer.push(arguments);}
| ^
24 | gtag('js', new Date());
25 |
26 | gtag('config', 'UA-47867706-3');
I wish they would just automatically escape stuff inside script
for us.
Finally to get page switches, you also have to track that with more code, see the Next.js answer mentioned above for an example.
Related: Adding script tag to React/JSX
Tested on react 17.0.2, next.js 10.2.2.
react-ga
only works with Universal Analytics, whereas new Google Analytics properties are GA4 properties by default. https://mcmap.net/q/182896/-google-analytics-4-with-react/9154668 – Zworykin