Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.