Created
September 26, 2019 20:56
-
-
Save karatechops/a03b089520866a175e3f61cabcb40044 to your computer and use it in GitHub Desktop.
React-ga Track component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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