Skip to content

Instantly share code, notes, and snippets.

@karatechops
Created September 26, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karatechops/a03b089520866a175e3f61cabcb40044 to your computer and use it in GitHub Desktop.
Save karatechops/a03b089520866a175e3f61cabcb40044 to your computer and use it in GitHub Desktop.
React-ga Track component
import React from 'react';
import PropTypes from 'prop-types';
import ReactGA from 'react-ga';
class Track extends React.Component {
constructor(props) {
super(props);
this.trackEvent = this.trackEvent.bind(this);
}
trackEvent() {
const { category, action, label, track } = this.props;
if (track) {
ReactGA.event({
category,
action,
label
});
}
}
render() {
const { NODE_ENV, GA_UA } = process.env;
return React.Children.map(
this.props.children,
child => React.cloneElement(
child,
{
...child.props,
onClick: () => {
if (child.props.onClick) {
child.props.onClick();
}
if (NODE_ENV === 'production' && GA_UA) {
this.trackEvent();
}
}
}
)
);
}
}
Track.propTypes = {
children: PropTypes.node.isRequired,
category: PropTypes.string, // Object interacted with "Video"
action: PropTypes.string, // Type of interaction "play"
label: PropTypes.any, // Category of event "Fall Campaign"
track: PropTypes.any,
};
Track.defaultProps = {
track: true
};
export default Track;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment