How can I add a GTM event handler on a button using React or Next?

Viewed 40

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;
0 Answers
Related