kyun
kyun

Reputation: 10264

script tag with Dynamic variables in Next.js

I'd like to add Google Analytics and Google Tag Manager on my web.

I'm trying to separate it as stages. (dev, prod)

_document.tsx

import Document, {Head, Main, NextScript } from 'next/document';
export default class MyDocument extends Document{
  render(){
    return (
      <html>
        <Head>
          {/* ... */}
          <script async src="http://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
          {/* ... */}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

What I expect

<script async src=`http://www.googletagmanager.com/gtag/js?id=${process.env.GTM_CONTAINER_ID}`></script>

I wanna use like above that.

Upvotes: 1

Views: 2147

Answers (1)

hangindev.com
hangindev.com

Reputation: 4873

Just like normal JSX, you use curly braces to embed a JavaScript expression in an attribute.

<script async src={`http://www.googletagmanager.com/gtag/js?id=${process.env.GTM_CONTAINER_ID}`}/>

Upvotes: 3

Related Questions