-
Notifications
You must be signed in to change notification settings - Fork 1
/
GAListenerActive.js
92 lines (77 loc) · 2.23 KB
/
GAListenerActive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React from "react";
import { PropTypes } from "prop-types";
import ReactGA from "react-ga";
import withLocationAndHistory from "../withLocationAndHistory";
class GAListenerActive extends React.Component {
componentDidMount() {
const { GACode } = this.props;
this.loadGoogleTag(GACode);
ReactGA.initialize(GACode, {
titleCase: false,
});
}
// Detect language change
componentDidUpdate(prevProps) {
if (prevProps.language !== this.props.language) {
this.sendLanguage();
}
}
manageHistory = () => {
const { history } = this.props;
this.sendPageView(history.location);
history.listen(this.sendPageView);
};
// Fired on route change
sendPageView = ({ pathname, hash }) => {
const page = `${pathname}${hash}`;
console.log(`event: Navigated to '${page}'`);
ReactGA.set({ page });
ReactGA.pageview(page);
};
sendLanguage = () => {
const { language } = this.props;
console.log(`event: Change language to '${language}'`);
ReactGA.set({ PageLanguage: language });
};
loadGoogleTag = (GACode) => {
// Global site tag (gtag.js) - Google Analytics
global.dataLayer = global.dataLayer || [];
global.gtag = function () {
global.dataLayer.push(arguments);
};
global.gtag("js", new Date());
global.gtag("config", GACode);
// Load GTag script async
const scriptTag = document.createElement("script");
scriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${GACode}`;
scriptTag.async = true;
scriptTag.onload = this.onScriptLoad;
document.body.appendChild(scriptTag);
};
onScriptLoad = () => {
this.sendLanguage();
this.manageHistory();
this.props.onLoad();
};
removeGA = () => {
this._ga = ReactGA.ga;
ReactGA.ga = null;
global.gtag = [];
global.dataLayer = [];
};
render() {
return this.props.children;
}
}
GAListenerActive.defaultProps = {
language: "en-en",
onLoad: () => {},
};
GAListenerActive.propTypes = {
language: PropTypes.string.isRequired,
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
onLoad: PropTypes.func.isRequired,
};
export default withLocationAndHistory(GAListenerActive);