Skip to content

Commit

Permalink
Implement tracking disable support (#15)
Browse files Browse the repository at this point in the history
* Upgrade to GA4

* Implement tracking disable support

* Change verison bump
  • Loading branch information
PauloMFJ authored Jul 17, 2021
1 parent c96c519 commit e53269d
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 10 deletions.
24 changes: 17 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A lightweight React library to implement custom Google Tag Manager events.

## Introduction

Designed to use and extend [Google Analytics 4](https://support.google.com/analytics/answer/10089681?hl=en). **Note**: If upgrading from react-gtm `0.0.6` or older, or currently using an older version of Google Analytics, you'll need to [upgrade](https://support.google.com/analytics/answer/9744165?hl=en). This library is also SSR safe and does not break when used without window existing.
Designed to use and extend [Google Analytics 4](https://support.google.com/analytics/answer/10089681?hl=en). **Note**: If upgrading from react-gtm `0.0.6` or older, or currently using an older version of Google Analytics, you'll need to [upgrade](https://support.google.com/analytics/answer/9744165?hl=en). This library is also SSR safe and does not break when used without window existing. This package is intended to be used with React / older Next.JS apps, for Next.JS 11 and above we recommend using [@phntms/next-gtm](https://www.npmjs.com/package/@phntms/next-gtm).

## Installation

Expand All @@ -22,9 +22,10 @@ npm i @phntms/react-gtm

### <TrackingHeadScript />

| Property | Type | Default | Required | Notes |
| -------- | -------- | --------- | -------- | ------------------------------------------------------------------------------- |
| **id** | `string` | undefined | **Yes** | ID that uniquely identifies GTM Container. Will be in the format; `GTM-xxxxxx`. |
| Property | Type | Default | Notes |
| ----------- | --------- | --------- | --------------------------------------------------------------------------------------------------------- |
| **id** | `string` | undefined | ID that uniquely identifies GTM Container. Example format: `GTM-xxxxxx`. |
| **disable** | `boolean` | false | Used to disable tracking events. Use if you want user to consent to being tracked before tracking events. |

To initialize GTM, add `TrackingHeadScript` to the `head` of the page.

Expand Down Expand Up @@ -60,9 +61,9 @@ export default class MyDocument extends Document {

### trackEvent()

| Parameter | Type | Default | Required | Notes |
| --------- | -------------------- | --------- | -------- | ----------------------------------------------- |
| props | `EventTrackingProps` | undefined | No | Custom tracking event to push to GTM container. |
| Parameter | Type | Default | Notes |
| --------- | -------------------- | --------- | ----------------------------------------------- |
| props | `EventTrackingProps` | undefined | Custom tracking event to push to GTM container. |

Example of a basic tracking event:

Expand All @@ -79,6 +80,15 @@ trackEvent({
});
```

### enableTracking()

| Parameter | Type | Default | Notes |
| ---------- | --------- | --------- | ------------------------------------------------------------------- |
| **id** | `string` | undefined | Same ID used in `trackingHeadScript`. Example format: `GTM-xxxxxx`. |
| **enable** | `boolean` | true | Used to enable or disable tracking events. |

**Note**: This _should_ only be used if needed, for example after user has consented to being tracked. You _shouldn't_ need to toggle this in normal usage.

### EventDataProps

| Parameter | Type | Default | Required | Notes |
Expand Down
4 changes: 3 additions & 1 deletion src/components/TrackingHeadScript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react";

import { EmbedTrackingProps } from "../types";

const TrackingHeadScript = ({ id }: EmbedTrackingProps) => (
const TrackingHeadScript = ({ id, disable = false }: EmbedTrackingProps) => (
<>
{id && (
<>
Expand All @@ -13,6 +13,8 @@ const TrackingHeadScript = ({ id }: EmbedTrackingProps) => (
<script>
{`
window.dataLayer = window.dataLayer || [];
window['ga-disable-${id}'] = ${disable.toString()};
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '${id}', { page_path: window.location.pathname });
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { default as TrackingHeadScript } from "./components/TrackingHeadScript";
export { default as trackEvent } from "./utils/trackEvent";
export { default as enableTracking } from "./utils/enableTracking";
export {
EmbedTrackingProps,
EventTrackingProps,
Expand Down
1 change: 1 addition & 0 deletions src/types.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export interface EmbedTrackingProps {
id?: string;
disable?: boolean;
}

export interface EventTrackingProps {
Expand Down
8 changes: 8 additions & 0 deletions src/utils/enableTracking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { IS_BROWSER } from "./platform";

const enableTracking = (id: string, enable = true) => {
if (!IS_BROWSER) return;
window[`ga-disable-${id}`] = (!enable).toString();
};

export default enableTracking;
34 changes: 33 additions & 1 deletion test/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react";

import TestRenderer from "react-test-renderer";

import { trackEvent, TrackingHeadScript } from "../src";
import { enableTracking, trackEvent, TrackingHeadScript } from "../src";
import { IS_BROWSER } from "../src/utils/platform";

const ID = "GTM-xxxxxx";
Expand All @@ -17,6 +17,26 @@ describe("<TrackingHeadScript />", () => {
const renderer = TestRenderer.create(<TrackingHeadScript />);
expect(renderer.toJSON()).toEqual(null);
});

it("disables tracking if disable prop is used", async () => {
const renderer = TestRenderer.create(
<TrackingHeadScript id={ID} disable />
);
expect(
JSON.stringify(renderer.toJSON()).includes(
`window['ga-disable-${ID}'] = true`
)
).toBe(true);
});

it("doesn't disable tracking if disable prop isn't used", async () => {
const renderer = TestRenderer.create(<TrackingHeadScript id={ID} />);
expect(
JSON.stringify(renderer.toJSON()).includes(
`window['ga-disable-${ID}'] = false`
)
).toEqual(true);
});
});

describe("trackEvent()", () => {
Expand Down Expand Up @@ -61,3 +81,15 @@ describe("trackEvent()", () => {
expect(window.dataLayer).toHaveLength(1);
});
});

describe("enableTracking()", () => {
it("enables tracking events if used", async () => {
enableTracking(ID);
expect(window[`ga-disable-${ID}`]).toEqual("false");
});

it("disables tracking events if enable is set to false", async () => {
enableTracking(ID, false);
expect(window[`ga-disable-${ID}`]).toEqual("true");
});
});
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"alwaysStrict": true,
"noImplicitReturns": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
"esModuleInterop": true,
"suppressImplicitAnyIndexErrors": true
},
"include": ["src/**/*.ts"],
"exclude": ["test/**/*"]
Expand Down

0 comments on commit e53269d

Please sign in to comment.