Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do integrate amplitude analytics with a React app?

Amplitude Analytics does provide Javascript SDK for Amplitude but how do I implement analytics in a React App where I don't have access to the DOM directly?

The GitHub page suggests to use amplitude.getInstance().logEvent('EVENT_IDENTIFIER_HERE') but in React I don't have an unique identifier of a component or a event.

like image 683
jasan Avatar asked Oct 03 '16 02:10

jasan


Video Answer


2 Answers

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!

like image 51
Albert Olivé Avatar answered Oct 13 '22 22:10

Albert Olivé


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)
like image 32
jasan Avatar answered Oct 13 '22 23:10

jasan