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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With