Skip to content

fix(strictmode): Fix for React in StrictMode causing a duplicate script registration #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 37 additions & 23 deletions example/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'react-app-polyfill/ie11'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom'
import {GTMProvider, useGTMDispatch} from '../dist'
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'
import { GTMProvider, useGTMDispatch } from '../dist'
import { createRoot } from 'react-dom/client'

const gtmParams = {
id: 'GTM-WH5NGGZ',
Expand All @@ -18,38 +18,42 @@ const App = (): JSX.Element => {
<GTMProvider state={gtmParams}>
<div>
<Routes>
<Route path="/push_on_mount" element={<RoutePushOnMount/>}/>
<Route path="/test" element={<TestRoute/>}/>
<Route path="/" element={<Homepage/>}/>
<Route path="/push_on_mount" element={<RoutePushOnMount />} />
<Route path="/test" element={<TestRoute />} />
<Route path="/" element={<Homepage />} />
</Routes>
</div>
</GTMProvider>
</Router>
)
}

const TestRoute = () => <>
<h2>Test route</h2>
<MyAwesomeButton/>
<br/>
<Link to="/">Home</Link>
</>
const TestRoute = () => (
<>
<h2>Test route</h2>
<MyAwesomeButton />
<br />
<Link to="/">Home</Link>
</>
)

const Homepage = () => <>
<h2>Homepage</h2>
<Link to="test">Test Route</Link>
<br/>
<br/>
<Link to="push_on_mount">Push on mount route</Link>
</>
const Homepage = () => (
<>
<h2>Homepage</h2>
<Link to="test">Test Route</Link>
<br />
<br />
<Link to="push_on_mount">Push on mount route</Link>
</>
)

const MyAwesomeButton = () => {
const sendDataToGTM = useGTMDispatch()

return (
<>
<p>The awesome button</p>
<button onClick={(): void => sendDataToGTM({event: 'my-custom-event'})}>Send Event</button>
<button onClick={(): void => sendDataToGTM({ event: 'my-custom-event' })}>Send Event</button>
</>
)
}
Expand All @@ -58,16 +62,26 @@ const RoutePushOnMount = () => {
const sendDataToGTM = useGTMDispatch()

React.useEffect(() => {
sendDataToGTM({event: 'push_on_mount', customData: 'custom_data'})
sendDataToGTM({ event: 'push_on_mount', customData: 'custom_data' })
})

return (
<>
<h2>Another route</h2>
<br/>
<br />
<Link to="/">Home</Link>
</>
)
}

ReactDOM.render(<App/>, document.getElementById('root'))
const container = document.getElementById('root')
if (container) {
const root = createRoot(container)
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
} else {
console.error('No container found')
}
5 changes: 3 additions & 2 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@
"alias": {
"react": "../node_modules/react",
"react-dom": "../node_modules/react-dom/profiling",
"react-dom/client": "../node_modules/react-dom/client",
"react-router-dom": "../node_modules/react-router-dom",
"scheduler/tracing": "../node_modules/scheduler/tracing-profiling"
},
"devDependencies": {
"@babel/core": "^7.17.8",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"@types/react": "18.3.5",
"@types/react-dom": "18.3.0",
"local-web-server": "^5.2.0",
"parcel": "^2.4.0",
"typescript": "^4.6.3"
Expand Down
24 changes: 9 additions & 15 deletions example/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -954,27 +954,21 @@
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.5.tgz#5f19d2b85a98e9558036f6a3cacc8819420f05cf"
integrity sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==

"@types/react-dom@^17.0.14":
version "17.0.20"
resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-17.0.20.tgz#e0c8901469d732b36d8473b40b679ad899da1b53"
integrity sha512-4pzIjSxDueZZ90F52mU3aPoogkHIoSIDG+oQ+wQK7Cy2B9S+MvOqY0uEA/qawKz381qrEDkvpwyt8Bm31I8sbA==
"@types/react-dom@18.3.0":
version "18.3.0"
resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.3.0.tgz#0cbc818755d87066ab6ca74fbedb2547d74a82b0"
integrity sha512-EhwApuTmMBmXuFOikhQLIBUn6uFg81SwLMOAUgodJF14SOBOCMdU04gDoYi0WOJJHD144TL32z4yDqCW3dnkQg==
dependencies:
"@types/react" "^17"
"@types/react" "*"

"@types/react@^17", "@types/react@^17.0.43":
version "17.0.58"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.58.tgz#c8bbc82114e5c29001548ebe8ed6c4ba4d3c9fb0"
integrity sha512-c1GzVY97P0fGxwGxhYq989j4XwlcHQoto6wQISOC2v6wm3h0PORRWJFHlkRjfGsiG3y1609WdQ+J+tKxvrEd6A==
"@types/react@*", "@types/react@18.3.5":
version "18.3.5"
resolved "https://registry.yarnpkg.com/@types/react/-/react-18.3.5.tgz#5f524c2ad2089c0ff372bbdabc77ca2c4dbadf8f"
integrity sha512-WeqMfGJLGuLCqHGYRGHxnKrXcTitc6L/nBUWfWPcTarG3t9PsquqUMuVeXZeca+mglY4Vo5GZjCi0A3Or2lnxA==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
csstype "^3.0.2"

"@types/scheduler@*":
version "0.16.3"
resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.3.tgz#cef09e3ec9af1d63d2a6cc5b383a737e24e6dcf5"
integrity sha512-5cJ8CB4yAx7BH1oMvdU0Jh9lrEXyPkar6F9G/ERswkCuvP4KQZfZkSjcMbAICCpQTN4OuZn8tz0HiKv9TGZgrQ==

"@types/semver@^7.3.12":
version "7.3.13"
resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.13.tgz#da4bfd73f49bd541d28920ab0e2bf0ee80f71c91"
Expand Down
15 changes: 8 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,24 @@
"@babel/core": "^7.17.8",
"@testing-library/react": "^12.1.4",
"@testing-library/react-hooks": "^7.0.2",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"@types/react": "18.3.5",
"@types/react-dom": "^18.3.0",
"all-contributors-cli": "^6.20.0",
"babel-jest": "^27.5.1",
"babel-plugin-module-resolver": "^4.1.0",
"eslint-plugin-prettier": "3.4.1",
"husky": "^7.0.4",
"prettier": "^2.6.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "6.26.1",
"react-test-renderer": "^17.0.2",
"tsdx": "^0.14.1",
"tslib": "^2.3.1",
"typescript": "^4.6.3"
},
"peerDependencies": {
"react": "^16.13.1 || ^17.0.0 || 18"
"react": "^16.13.1 || ^17.0.0 || ^18.0.0"
},
"husky": {
"hooks": {
Expand Down Expand Up @@ -80,5 +80,6 @@
"src"
]
},
"dependencies": {}
"dependencies": {},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
11 changes: 9 additions & 2 deletions src/models/GoogleTagManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,23 @@ export type ICustomEnvironmentParams = {
/**
* The shape of the GTM Snippets params
*/

export type ISnippetsParams = {
/** The data layer object to be used */
dataLayer?: Pick<IDataLayer, 'dataLayer'>['dataLayer']
/** The name of the data layer variable */
dataLayerName?: Pick<IDataLayer, 'dataLayerName'>['dataLayerName']
/** Custom environment parameters */
environment?: ICustomEnvironmentParams
/** Nonce attribute for the script tag */
nonce?: string
/** Google Tag Manager container ID */
id: string
/** Whether to inject the GTM script. Defaults to true */
injectScript?: boolean
/** Defaults to https://www.googletagmanager.com */
/** Custom domain for the GTM script. Defaults to https://www.googletagmanager.com */
customDomain?: string
/** Defaults to gtm.js */
/** Custom script name. Defaults to gtm.js */
customScriptName?: string
}

Expand Down
58 changes: 29 additions & 29 deletions src/utils/GoogleTagManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,38 +45,38 @@ const setupGTM = (params: ISnippetsParams): ISetupGTM => {

/**
* Function to init the GTM
* @param dataLayer - The dataLayer
* @param dataLayerName - The dataLayer name
* @param environment - Specify the custom environment to use
* @param nonce - Server-generated nonce
* @param id - The ID of the GTM
* @param config - The shape of the GTM Snippets params
*/
export const initGTM = ({
dataLayer,
dataLayerName,
environment,
nonce,
id,
customDomain,
customScriptName
}: ISnippetsParams): void => {
const gtm = setupGTM({
dataLayer,
dataLayerName,
environment,
nonce,
id,
customDomain,
customScriptName
})
export const initGTM = (config: ISnippetsParams): void => {
const gtm = setupGTM(config)

const insertScripts = (doc: Document) => {
try {
// Remove existing GTM scripts if they exist
['script[data-gtm-data-layer]', 'script[data-gtm-script]', 'noscript[data-gtm-noscript]'].forEach(selector => {
const existingElement = doc.querySelector(selector);
if (existingElement) existingElement.remove();
});

const dataLayerScript = gtm.getDataLayerScript();
const script = gtm.getScript();
const noScript = gtm.getNoScript();

const dataLayerScript = gtm.getDataLayerScript()
const script = gtm.getScript()
const noScript = gtm.getNoScript()
doc.head.insertBefore(dataLayerScript, doc.head.childNodes[0]);
doc.head.insertBefore(script, doc.head.childNodes[1]);
doc.body.insertBefore(noScript, doc.body.childNodes[0]);

// Add data attributes to identify the scripts
dataLayerScript.setAttribute('data-gtm-data-layer', '');
script.setAttribute('data-gtm-script', '');
noScript.setAttribute('data-gtm-noscript', '');

} catch (error) {
console.error('Error initializing GTM:', error);
}
};

document.head.insertBefore(dataLayerScript, document.head.childNodes[0])
document.head.insertBefore(script, document.head.childNodes[1])
document.body.insertBefore(noScript, document.body.childNodes[0])
insertScripts(document);
}

/**
Expand Down
Loading