How do I add/activate analytics scripts on a button click?
I have analytics scripts I need to add to a next.js website only if the user opts in.
On the click of a button in my CookieBanner
component I set a cookie to record if they've opted in. At this point I also want to then append the script tags to the Head element:
import Link from "next/link";
import cookie from "js-cookie";
import React, { useState, useEffect } from 'react';
export default function CookieBanner() {
// // Set a cookie to hide the banner
const [showBanner, setBanner] = useState(true);
const handleBanner = (setOptIn) => {
// Hide banner
setBanner(false);
// Set cookies
updateGDPR(setOptIn);
}
function updateGDPR(gdprState) {
gdprState ? cookie.set('gdprOptIn', true) : cookie.set('gdprOptIn', false);
document.head.innerHTML += document.head.innerHTML + `
<script>
/* <!-- Hotjar Tracking Code for my site --> */
(function(h,o,t,j,a,r){
My Hotjar code here
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-MY G TAG HERE');
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-MY G TAG HERE"></script>`
return;
}
return (
<div className={`cookie-banner ${!showBanner ? 'hide-banner' : ''}`} id="cookieBanner">
<div className="cookie-card">
<h1>Cookies</h1>
<p>We’d like to use analytics cookies so we can understand how you use the website and make improvements.</p>
<p>We also use essential cookies to remember if you’ve accepted analytics cookies. <Link href={'/privacy/cookies'}>Learn more</Link></p>
<form className="button-wrapper">
<button value={'accept'} type="button" className='btn btn-primary' onClick={()=>{handleBanner(true)}}>Accept all</button>
<button value={'reject'} type="button" className='btn btn-primary' onClick={()=>{handleBanner(false)}}>Reject</button>
</form>
</div>
</div>
)
}
However nothing is then firing as I move around the site despite the tags being in place.
On a refresh or initial load everything works as it should. In this case the script tags being added in the _app.js file if opted in, which I know via a cookie that is set on the button click:
export default function App({ Component, pageProps }) {
return (
<>
{pageProps.analytics.setAnalytics ?
<>
<Head>
{/* Hotjar */}
<script
dangerouslySetInnerHTML={{__html: ``
/* <!-- Hotjar Tracking Code for my site --> */
(function(h,o,t,j,a,r){
CODE HERE
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');`
}}
/>
{/* Google Analytics */}
<script
dangerouslySetInnerHTML={{__html:
`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MY G TAG HERE');`}}
/>
</Head>
<Script id='ga_tagmanager'
strategy='afterInteractive'
async
src="https://www.googletagmanager.com/gtag/js?id=MY ID HERE"/>
</>
:''}
{(pageProps.analytics == undefined || pageProps.analytics.showCookieBanner == true) &&
<CookieBanner></CookieBanner>
}
<Component {...pageProps} />
</>
You should at first create script tag:
const script = document.createElement('script');
script.innerHTML = ` /* <!-- Hotjar Tracking Code for my site --> */
(function(h,o,t,j,a,r){
My Hotjar code here
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-MY G TAG HERE');`
And then append it to head.
document.head.appendChild(script);