holidaycheck / react-google-tag-manager

This repository contains a react based implementation for Google's Tag Manager snippet.
MIT License
192 stars 31 forks source link

TypeScript not support #78

Open shinriyo opened 6 years ago

shinriyo commented 6 years ago

Try npm install @types/react-tag-manager if it exists or add a new declaration (.d.ts) file containing declare module 'react-tag-manager';

poteirard commented 5 years ago

Hi I just added this snippet to my code:

declare module 'react-google-tag-manager' {
  export interface IConfig {
    dataLayerName?: string;
    scriptId?: string;
    gtmId?: string;
    additionalEvents?: object;
    previewVariables?: boolean;
    scheme?: string;
  }
  export interface  IGTMParts {
    noScriptAsReact: () => HTMLElement;
    noScriptAsHTML: () => string;
    scriptAsReact: () => HTMLScriptElement;
    scriptAsHTML: () => string;
  }
  export default function GTMParts(...IConfig): IGTMParts;
}

I would also be happy to make a PR to change to migrate the library to Typescript if the owner of the library agrees (@holidaycheck) and it's useful. Or to add the types at least.

EdmundMai commented 5 years ago

In case this helps anyone this is a Typescript version of the component in the readme:

import React, { useEffect } from "react";
import gtmParts from "react-google-tag-manager";

interface IProps {
  gtmId: string;
  dataLayerName?: string;
  additionalEvents?: any;
  previewVariables?: string;
  scriptId?: string;
  scheme?: string;
}

const GoogleTagManager = (props: IProps) => {
  useEffect(() => {
    const dataLayerName = props.dataLayerName || "dataLayer";
    const scriptId = props.scriptId || "react-google-tag-manager-gtm";

    if (!window[dataLayerName]) {
      const script = document.createElement("script");
      const gtmScriptNode = document.getElementById(scriptId);

      if (gtmScriptNode) {
        const scriptText = document.createTextNode(
          gtmScriptNode.textContent || ""
        );

        script.appendChild(scriptText);
        document.head.appendChild(script);
      }
    }
  }, []);

  const gtm = gtmParts({
    id: props.gtmId,
    dataLayerName: props.dataLayerName || "dataLayer",
    additionalEvents: props.additionalEvents || {},
    previewVariables: props.previewVariables || false,
    scheme: props.scheme || "https:"
  });

  return (
    <div>
      <div>{gtm.noScriptAsReact()}</div>
      <div id={props.scriptId || "react-google-tag-manager-gtm"}>
        {gtm.scriptAsReact()}
      </div>
    </div>
  );
};

export default GoogleTagManager;