Search code examples
javascriptreactjsnext.jshead

How to capture date in next js head?


I am trying to access Date.now() within a script tag inside a head section. I am using the following snippet of code:-

import Link from "next/link";
import Head from "next/head";

export default function IndexPage() {
  return (
    <div>
      <Head>
        <script
          // eslint-disable-next-line react/no-danger
          dangerouslySetInnerHTML={{
            __html: `
                  document.write("\x3Cscript src="https://somerandomeurl/initialize_pixel.js?v=' + Date.now() + '">\x3C/script>");`
          }}
        ></script>
      </Head>
      Hello World.{" "}
      <Link href="/about">
        <a>About</a>
      </Link>
    </div>
  );
}

When I run this code I get the following output:-

'); Hello World. About

How can I get the date and avoid printing '); on the screen?


Solution

  • Just use template strings:

    <Head>
       <script src={`https://somerandomeurl/initialize_pixel.js?v=${Date.now()}`}></script>
    </Head>