Skip to content

Commit 12c3695

Browse files
fix: load initial script
1 parent ac481a1 commit 12c3695

6 files changed

Lines changed: 748 additions & 685 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# [Versions](https://github.com/Tracktor/react-google-tag-manager/releases)
22

3-
## v1.2.1
4-
- **[REFACTOR]** : change `vite-plugin-dts `as devDependencies
3+
## v1.2.3
4+
- **[fix]** : load initial script

README.md

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22

33
[![npm version](https://badge.fury.io/js/%40tracktor%2Freact-google-tag-manager.svg)](https://badge.fury.io/js/%40tracktor%2Freact-google-tag-manager)
44

5-
**React library for use easily the Google Tag Manager**
5+
**Very light React library for use easily the Google Tag Manager**
66

77

88
- [Installation](#Installation)
99
- [Usage](#Usage)
10-
- [Options](#Options)
10+
- [Props and options](#Props-and-Options)
11+
- [Hooks](#kook)
1112

1213
## Installation
1314

@@ -48,9 +49,10 @@ const YourComponent = () => {
4849

4950
export default App;
5051
```
51-
## Options
5252

53-
Your can provide some options to the provider.
53+
## Props and options
54+
55+
Your can provide some props and options to the provider.
5456

5557
```typescript jsx
5658
import { GoogleTagManagerProvider } from "@tracktor/react-google-tag-manager";
@@ -63,10 +65,21 @@ const App = () => (
6365

6466
export default App;
6567
```
68+
| Props | Type | Default | Description |
69+
|---------|------------|-----------|-------------------------------------------------------------------------------------------------------------------------------|
70+
| id | GTM-XXXXXX | undefined | Define the Google Tag Manager ID id. You can create an account to get an ID here : https://tagmanager.google.com/?hl=fr#/home |
71+
| options | object | undefined | Provider options |
72+
6673

74+
| Option | Type | Default | Description |
75+
|---------------|--------|-----------------------------------------|-------------------------|
76+
| scriptUrl | string | https://www.googletagmanager.com/gtm.js | Set script url to load |
77+
| dataLayerName | string | dataLayer | Set the data layer name |
6778

68-
| Option | Type | Default | Description |
69-
|---------------|--------|------------------------------------------|-------------------------|
70-
| scriptUrl | string | https://www.googletagmanager.com/gtag/js | Set script url to load |
71-
| dataLayerName | string | dataLayer | Set the data layer name |
79+
## Hooks
80+
`useGoogleTagManager`
7281

82+
| Export | type | Description |
83+
|-----------|----------|----------------|
84+
| sendEvent | function | Send GTM event |
85+
| id | string | The GTM id |

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@tracktor/react-google-tag-manager",
33
"description": "React library for use easily the Google Tag Manager",
4-
"version": "1.2.1",
4+
"version": "1.2.3",
55
"private": false,
66
"license": "ISC",
77
"type": "module",
@@ -35,7 +35,7 @@
3535
"prepare": "yarn run build && husky install"
3636
},
3737
"dependencies": {
38-
"@tracktor/react-utils": "^1.7.0",
38+
"@tracktor/react-utils": "^1.9.0",
3939
"react": "^18.2.0",
4040
"react-dom": "^18.2.0"
4141
},

src/context/GoogleTagManagerProvider.tsx

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,63 @@
1-
import { useScript } from "@tracktor/react-utils";
2-
import { createContext, ReactNode, useMemo } from "react";
1+
import { useIsomorphicLayoutEffect, useScript } from "@tracktor/react-utils";
2+
import { createContext, ReactNode, useMemo, useRef } from "react";
3+
import { injectDataLayer, createNoScript } from "@/utils/utilsGTM";
34

45
interface GoogleTagManagerProviderProps {
5-
id: string;
6+
id?: `GTM-${string}` | string;
67
options?: {
78
scriptUrl?: string;
89
dataLayerName?: string;
910
};
1011
children: ReactNode;
1112
}
1213

13-
const DEFAULT_SCRIPT_URL = "https://www.googletagmanager.com/gtag/js";
14-
const DEFAULT_DATA_LAYER_NAME = "dataLayer";
14+
interface DefaultContextValue {
15+
id?: GoogleTagManagerProviderProps["id"];
16+
options: {
17+
scriptUrl: string;
18+
dataLayerName: string;
19+
};
20+
}
1521

16-
export const GoogleTagManagerContext = createContext({
17-
id: "",
22+
const defaultContextValue = {
23+
id: undefined,
1824
options: {
19-
dataLayerName: DEFAULT_DATA_LAYER_NAME,
20-
scriptUrl: DEFAULT_SCRIPT_URL,
25+
dataLayerName: "dataLayer",
26+
scriptUrl: "https://www.googletagmanager.com/gtm.js",
2127
},
22-
});
28+
};
29+
30+
export const GoogleTagManagerContext = createContext<DefaultContextValue>(defaultContextValue);
2331

2432
const GoogleTagManagerProvider = ({ children, id, options }: GoogleTagManagerProviderProps) => {
33+
const { dataLayerName, scriptUrl } = { ...options, ...defaultContextValue.options };
34+
const isInitialized = useRef<boolean>(false);
35+
2536
const value = useMemo(
2637
() => ({
2738
id,
2839
options: {
29-
dataLayerName: options?.dataLayerName || DEFAULT_DATA_LAYER_NAME,
30-
scriptUrl: options?.scriptUrl || DEFAULT_SCRIPT_URL,
40+
dataLayerName,
41+
scriptUrl,
3142
},
3243
}),
33-
[id, options]
44+
[dataLayerName, id, scriptUrl]
3445
);
3546

47+
// Initialize GTM
48+
useIsomorphicLayoutEffect(() => {
49+
if (!id || isInitialized.current) {
50+
return;
51+
}
52+
53+
isInitialized.current = true;
54+
55+
injectDataLayer(dataLayerName);
56+
createNoScript(id);
57+
}, [dataLayerName, id]);
58+
3659
// Load the script asynchronously
37-
useScript(`${value.options.scriptUrl}?id=${value.id}`, !!value.id);
60+
useScript(`${value.options.scriptUrl}?id=${value.id}`, { enable: !!value.id, position: "head-start" });
3861

3962
return <GoogleTagManagerContext.Provider value={value}>{children}</GoogleTagManagerContext.Provider>;
4063
};

src/utils/utilsGTM.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Create the GTM noscript tag
3+
* @param id
4+
*/
5+
export const createNoScript = (id: string) => {
6+
// Create additional noscript tag
7+
const noscript = document.createElement("noscript");
8+
const iframe = document.createElement("iframe");
9+
10+
iframe.src = `https://www.googletagmanager.com/ns.html?id=${id}`;
11+
iframe.height = "0";
12+
iframe.width = "0";
13+
iframe.style.display = "none";
14+
iframe.style.visibility = "hidden";
15+
16+
noscript.appendChild(iframe);
17+
document.body.insertBefore(noscript, document.body.childNodes[0]);
18+
};
19+
20+
/**
21+
* Inject the dataLayer
22+
* @param dataLayerName
23+
*/
24+
export const injectDataLayer = (dataLayerName: string) => {
25+
window[dataLayerName] = window[dataLayerName] || [];
26+
window[dataLayerName].push({ event: "gtm.js", "gtm.start": new Date().getTime() });
27+
};

0 commit comments

Comments
 (0)