Skip to content

Provide a 'withMetrics' HOC to abstract react context #52

Description

@ramesius

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions