Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryanwilsonperkin
Last active August 14, 2018 18:38
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 ryanwilsonperkin/fe8633ab4118299b3fa7e455eea81b71 to your computer and use it in GitHub Desktop.
Save ryanwilsonperkin/fe8633ab4118299b3fa7e455eea81b71 to your computer and use it in GitHub Desktop.
A HOC proposal for injecting tracking of events.
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);
function trackEvent(eventName, businessId, countryName) {
// Build and send XHR event to Amplitude
}
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