14

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.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
jasan
  • 11,475
  • 22
  • 57
  • 97

5 Answers5

32

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!

Albert Olivé Corbella
  • 4,061
  • 7
  • 48
  • 66
  • 2
    in case anyone stumbles across this again, the import is slightly different now. It's simply `import amplitude from 'amplitude-js';` – philarmour Oct 30 '20 at 17:16
4

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)
jasan
  • 11,475
  • 22
  • 57
  • 97
2

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.

ryanashcraft
  • 131
  • 1
  • 8
  • 7
    This library was abandoned as of 26 Jun 2019 (latest commit). Several issues have been opened since with no response. It still uses componentWillMount and componentWillUpdateProps, which are both deprecated and will stop working in React 17.x – gatlanticus Sep 29 '19 at 23:57
0

For those who are using @amplitude/analytics-browser with NextJS, the getInstance() is not used:

import * as amplitude from "@amplitude/analytics-browser";

// Custom Amplitude config
const config = {};

export const initAmplitude = () => {
  amplitude.init(AMPLITUDE_PROJECT_ID, undefined, config);
};

export const trackAmplitudeData = (eventType: string | amplitude.Types.BaseEvent, eventProperties?: Record<string, unknown>) => {
  amplitude.track(eventType, eventProperties);
};

Then in _app.tsx initialize Amplitude like this:

  useEffect(() => {
    if (router.isReady) {
      initAmplitude();
    }
  }, []);
Bassem
  • 3,582
  • 2
  • 24
  • 47
-1

I suggest using the Segment analytics library and following our React quickstart guide. You can track page visits with react-router and user behavior all within React components. You’ll be able to turn on Amplitude via our dashboard, and have access to 250+ other destinations. Here is an example of using a React event handler:

export default class SignupButton extends Component {
  trackEvent() {
    window.analytics.track('User Signup');
  }

  render() {
    return (
      <button onClick={this.trackEvent}>
        Signup with Segment today!
      </button>
    );
  }
}

I’m the maintainer of https://github.com/segmentio/analytics-react. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools without having to write any additional code.

William
  • 87
  • 4