1

In my Next app, I am using react-gtm-module with GTM ID. Now I want an event handler on the button so that when it is clicked, an event should be added to the Google Tag Manager data layer.

export const MyButton = () => (
  <button
    onClick={() => {
      window.dataLayer.push({ event: "some-event" });
    }}
  >
    Click Me!
  </button>
);

But it is giving me the error "Type error: Property 'dataLayer' does not exist on type 'Window & type of globalThis'."

In _app.tsx I have initialized GTM with the following code:

import type { AppProps } from "next/app";
import { useEffect } from "react";
import TagManager from "react-gtm-module";

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    TagManager.initialize({
      gtmId: "GTM-XXXXXXX",
      events: {
        sendUserInfo: "userInfo",
      },
      dataLayer: {
        userId: "001",
        userProject: "project",
      },
    });
  }, []);
return <Component {...pageProps} />;
}

export default MyApp;
rioV8
  • 24,506
  • 3
  • 32
  • 49
  • You need to declare the `dataLayer` property on the `window` type, i.e. `declare global { interface Window { dataLayer: any[]; } }`. See [How do you explicitly set a new property on `window` in TypeScript?](https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript). – juliomalves Jul 03 '22 at 21:01

0 Answers0