react-metrics icon indicating copy to clipboard operation
react-metrics copied to clipboard

Provide a 'withMetrics' HOC to abstract react context

Open ramesius opened this issue 8 years ago • 2 comments

The catalyst of this request comes from me stumbling across this from Dan Abramov: https://twitter.com/dan_abramov/status/749715530454622208

Backing this up, the react docs recommend not to use the context directly https://facebook.github.io/react/docs/context.html#why-not-to-use-context

I propose a "withMetrics" higher order component that accepts a react-redux style 'mapMetricsToProps' function to map metrics API functions to a components props.

import React from 'react';
import { withMetrics } from 'react-metrics';

class TopCheckoutButton extends React.Component {
 render() {
  const { trackCheckout } = this.props;
  return <button onClick={() => trackCheckout('top')} />;
 }
}

class BottomCheckoutButton extends React.Component {
 render() {
  const { trackCheckout } = this.props;
  return <button onClick={() => trackCheckout('bottom')} />;
 }
}

function trackCheckoutEvent(metrics) {
 return (checkoutButtonPosition) => {
  return metrics.track(`checkout_${checkoutButtonPosition}`);
 };
}

function mapMetricsToProps(metrics) {
 return {
  trackCheckout: trackCheckoutEvent(metrics)
 }
}

const TrackedTopCheckoutButton = withMetrics(mapMetricsToProps)(TopCheckoutButton);
const TrackedBottomCheckoutButton = withMetrics(mapMetricsToProps)(BottomCheckoutButton);

export TrackedTopCheckoutButton;
export TrackedBottomCheckoutButton;

The above example demonstrates the usage of such a HOC to compose tracked checkout buttons using a common curried function that wraps the track() call from react-metrics.

A more simplistic example would be exposing the react-metrics API functions directly to the wrapped component

export default withMetrics(metrics => { trackSomething: metrics.track })(MyTrackedComponent); // Named tracking methods
export default withMetrics()(MyOtherTrackedComponent); // Default passing all react-metrics api functions as props

Interested to know if this feature sounds reasonable to implement directly into this repository and if you would accept PRs for such a feature.

ramesius avatar Aug 26 '17 04:08 ramesius

Definitely sounds like a worthwhile refactor!

potench avatar Aug 26 '17 04:08 potench

I can start working on a PR for the above feature, though I can potentially see some wider refactoring to reduce the ambiguity of a exposeMetrics and withMetrics function.

ramesius avatar Aug 28 '17 23:08 ramesius