I have a problem with a inline condition for loading scripts. The conditions works because the tag shows me de text but for script it doesn't works. How can I solve it.
const cookie = new Cookies().get('cookiesAccepted');
const [loadScript,setLoadScript]= useState(cookie);
function cookieAccepted(){
setLoadScript(true);
}
return(
{loadScript &&
<h1>test</h1>
}
<Cookie meta={cookieAccepted.bind(this)}/>
{ loadScript &&
<script
async
src="https://www.googletagmanager.com/gtag/"
/>
}
{loadScript &&
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '********', {
page_path: window.location.pathname,
});
`,
}}
/>
}
)
I recommend using the Script function from next js.
import Script from 'next/script';
Instead of adding tag, you could be doing something like this:
{cookieAccepted && (
<Script src={`https://www.googletagmanager.com/gtag/`}/>
)}
Check this link for more references: https://nextjs.org/docs/api-reference/next/script