amplitude / react-amplitude

A React component library for easy product analytics instrumentation (deprecated)
Other
118 stars 14 forks source link

[RFC] AmplitudeHookProvider component proposal #24

Open mattiaerre opened 4 years ago

mattiaerre commented 4 years ago

Description

Code

import { Amplitude, AmplitudeProvider } from '@amplitude/react-amplitude';
import amplitude from 'amplitude-js';
import React, { createContext, useContext } from 'react';

export const AmplitudeContext = createContext();

export function useAmplitude() {
  return useContext(AmplitudeContext);
}

function AmplitudeHookProvider({ apiKey, children }) {
  return (
    <AmplitudeProvider
      amplitudeInstance={amplitude.getInstance()}
      apiKey={apiKey}
    >
      <Amplitude>
        {props => {
          return (
            <AmplitudeContext.Provider value={props}>
              {children}
            </AmplitudeContext.Provider>
          );
        }}
      </Amplitude>
    </AmplitudeProvider>
  );
}

export default AmplitudeHookProvider;

Usage

ReactDOM.render(
  <AmplitudeHookProvider apiKey={REACT_APP_AMPLITUDE_KEY}>
    <App />
  </AmplitudeHookProvider>,
  document.getElementById('root')
);
function Item({ counter, tag }) {
  const { logEvent } = useAmplitude();
  const { properties, type } = viewCollection;
  return (
      <Link
        onClick={() => {
          logEvent(type, properties({ counter, tag }));
        }}
        to={`/${tag.slug}`}
      >
        {tag.name}
      </Link>
  );
}
mattiaerre commented 4 years ago

I am working on a React app that uses hooks and I've come up with this solution to use the logEvent function w/o having to decorate my components w/ the <Amplitude /> wrapper, let me know what you think. It'd be nice if you could integrate something similar into the main library; I'd be more than happy to create also a PR for that; thanks btw for the amplitude client and utilities 🙏

mattiaerre commented 4 years ago

oh, I think there is already another package that does it: https://github.com/koblas/react-amplitude-hooks // cc @koblas