I have a React app and now I need to include the Google Tag Manager in my app. I have two environments as dev and prod. Google provides two different code fragments for the two environments, So as far as I know, these code fragments need to be included inside the .env file and need to be included inside the index.html with the syntax "%REACT_APP_%
" So I tried as follows
.env
REACT_APP_GOOGLE_TAG_MANAGER_HEAD=<!-- Google Tag Manager -->
<script>(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-KW2QJK3');</script>
<!-- End Google Tag Manager -->
When I do this, only the first line is taken as the code and I think that because the compiler doesn't identify multiple lines of declarations. So here are the two solutions I identified so far.
I need to know that, is there any other better method to get this done? Like is there any way to define a code fragment inside .env or declare multiple lines for a single variable?
Try using react-gtm-module, it worked for me and is a clean way to do it.