Open shinriyo opened 6 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.
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;
Try
npm install @types/react-tag-manager
if it exists or add a new declaration (.d.ts) file containingdeclare module 'react-tag-manager';