How do integrate amplitude analytics with a React app?

Amplitude recently released an experimental library called "react-amplitude" specifically for integrating Amplitude into React web apps. It provides a few React components for declaratively logging events and setting event and user properties. See the announcement blog post and the GitHub repo for more info.


This is what I did and works perfectly:

yarn add amplitude-js

utilities/amplitude.js

import amplitude from 'amplitude-js';

export const initAmplitude = () => {
  amplitude.getInstance().init(process.env.REACT_APP_AMPLITUDE);
};

export const setAmplitudeUserDevice = installationToken => {
  amplitude.getInstance().setDeviceId(installationToken);
};

export const setAmplitudeUserId = userId => {
  amplitude.getInstance().setUserId(userId);
};

export const setAmplitudeUserProperties = properties => {
  amplitude.getInstance().setUserProperties(properties);
};

export const sendAmplitudeData = (eventType, eventProperties) => {
  amplitude.getInstance().logEvent(eventType, eventProperties);
};

index.js

...

import { initAmplitude } from './utilities/amplitude';

initAmplitude();

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <Provider store={store}>
      <Routes store={store} />
    </Provider>
  </ThemeProvider>,
  document.getElementById('root')
);

And then you're good to go. Call the other methods when you need it, like setAmplitudeUserDevice:

import { setAmplitudeUserDevice } from 'utilities/amplitude';

export function installationInitializationSuccess(id, token) {
  setAmplitudeUserDevice(token);

  return {
    type: INSTALLATION_INITIALIZATION_SUCCESS,
    id,
    token
  };
}

Hope it helps!


The 'EVENT_IDENTIFIER_HERE' is actually just any arbitrary but unique name(label) for the event that you want to log. So when you check the amplitude dashboard you are able to find events easily.

i.e amplitude.getInstance().logEvent('visitedHomePage') or amplitude.getInstance().logEvent('cartButtonClicked') etc.

furthermore you can pass extra eventData along with the event like so:

amplitude.getInstance().logEvent('cartButtonClicked', itemsInCart)