Last active
August 14, 2018 18:38
-
-
Save ryanwilsonperkin/fe8633ab4118299b3fa7e455eea81b71 to your computer and use it in GitHub Desktop.
A HOC proposal for injecting tracking of events.
This file contains hidden or 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 withTracking from 'withTracking'; | |
export class MyLink extends React.Component { | |
static propTypes = { | |
text: PropTypes.string, | |
href: PropTypes.string, | |
track: PropTypes.func, | |
}; | |
onClick() { | |
this.props.track('w/web/mylink/clicked'); | |
} | |
render() { | |
return <a href={this.props.href} onclick={this.onClick}>{this.props.text}</a> | |
} | |
} | |
export default withTracking(MyLink); |
This file contains hidden or 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
function trackEvent(eventName, businessId, countryName) { | |
// Build and send XHR event to Amplitude | |
} |
This file contains hidden or 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 { connect } from 'react-redux'; | |
import trackEvent from 'track'; | |
// HOC: Wraps a component and injects a `track` prop for callback. | |
export default function withTracking(WrappedComponent) { | |
const Tracker = class extends React.Component { | |
track(eventName) { | |
// Gracefully handle things if the store doesn't exist. | |
// This could happen if we're testing a React tree without using redux or a mockStore in the test. | |
const businessId = this.props.store ? this.props.store.get('businessId') : undefined; | |
const countryName = this.props.store ? this.props.store.get('countryName') : undefined; | |
// Defer to the "trackEvent" for actually sending the event. | |
trackEvent(eventName, businessId, countryName); | |
} | |
render() { | |
return <WrappedComponent track={this.track} {...this.props} />; | |
} | |
}; | |
return connect()(Tracker); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment