React Native
Amplitude React Native SDK Installation & Quick Start
SDK Installation
Add dependencies
Run yarn add @amplitude/react-native in your project directory, the same level with package.json.
yarn add @amplitude/[email protected]
iOS Installation
cd /ios && pod install
Usage & Examples
Initialization
Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required.
import * as React from 'react';
import { Button } from 'react-native';
import { Amplitude, Identify } from '@amplitude/react-native';
const ampInstance = Amplitude.getInstance();
ampInstance.init(API_KEY);
export function MyApp() {
return (
<Button
title="Log Event"
onPress={() => ampInstance.logEvent('BUTTON_CLICKED')}
/>
);
}
EU Data Residency
Starting from version 2.6.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. SDK will switch and send data based on the server zone if it is set. The server zone config supports dynamic configuration as well.
For previous versions, you need to configure the serverURL property after initializing the client.
Warning: For EU data residency, project need to be set up inside Amplitude EU and SDK initialized with api key from Amplitude EU first. This method won't work without proper set up first.
// For versions starting from 2.6.0
// No need to call setServerUrl for sending data to Amplitude's EU servers
Amplitude.getInstance().setServerZone('EU');
// For earlier versions
Amplitude.getInstance().setServerUrl("https://api.eu.amplitude.com"));
Sending Events
Basic Events
Events represent how users interact with your application. For example, “button clicked” may be an action you want to track.
Amplitude.getInstance().logEvent('BUTTON_CLICKED');
Events with Properties
Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “button click”
Amplitude.getInstance().logEvent("BUTTON_CLICKED", {"Hover Time": "100ms"});
Flush Events
Events are typically stored in a buffer and flushed periodically. This behavior is configurable. You can also flush events manually
Amplitude.getInstance().uploadEvents();
User Properties
User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language. Amplitude-ReactNative's Identify class manages these features. You need to import the Identify
before using it.
import { Identify } from '@amplitude/react-native';
IMPORTANT NOTE
Please be sure to not track any user data that may be against your privacy terms.
Setting a User Property
setUserId
set
set
sets the value of a user property. You can also chain together multiple identify calls.
const identify = new Identify();
identify.set("gender", "female").set("age", 20);
Amplitude.getInstance().identify(identify);
setOnce
setOnce
sets the value of a user property only once. Subsequent calls using setOnce
will be ignored.
const identify1 = new Identify();
identify1.setOnce("sign_up_date", "2015-08-24");
Amplitude.getInstance().identify(identify1);
const identify2 = new Identify();
identify2.setOnce("sign_up_date", "2015-08-24");
Amplitude.getInstance().identify(identify2);// is ignored
add
add
increments a user property by some numerical value. If the user property does not have a value set yet, it will be initialized to 0 before being incremented.
const identify = new Identify();
identify.add("karma", 0.123);
Amplitude.getInstance().identify(identify);
Setting multiple user properties
You can use setUserProperties
as a shorthand to set multiple user properties at once. This method is simply a wrapper around Identify.set
and identify
.
const userProperties = {
"KEY": "VALUE",
"OTHER_KEY": "OTHER_VALUE",
}
Amplitude.getInstance().setUserProperties(userProperties);
Arrays in user properties
Arrays can be used as user properties. You can directly set arrays or use append to generate an array.
const colors = ["rose", "gold"];
const numbers = [4, 5];
const identify = new Identify();
identify.set("colors", colors)
.append("ab-tests", "campaign_a")
.append("existing_list", numbers);
Amplitude.getInstance().identify(identify);
append
append
will append a value or values to a user property array.
If the user property does not have a value set yet, it will be initialized to an empty list before the new values are added. If the user property has an existing value and it is not a list, it will be converted into a list with the new value added.
const array = ["some_string", 56];
const identify = new Identify();
identify.append("ab-tests", "new-user-test")
Amplitude.getInstance().identify(identify);
Removing User Properties
Clearing All User Properties
clearUserProperties
will wipe all of the current user's user properties.
The result is irreversible!
Amplitude will not be able to sync the user's user property values before the wipe to any future events that the user triggers as they will have been reset.
Amplitude.getInstance().clearUserProperties();
remove
remove
will remove a value or values to a user property, if it does exist in the user property. Remove means remove the existing value(s) from the given list. If the item does not exist in the user property, there will be no operation.
const array = ["some_string", 56];
const identify = new Identify();
identify.remove("ab-tests", "new-user-test")
.remove("some_list",array);
Amplitude.getInstance().identify(identify);
unset
unset
unsets and removes a user property.
const identify = new Identify();
identify.unset("karma").unset("gender");
Amplitude.getInstance().identify(identify);
Track Revenue
Amplitude can track revenue generated by a user. Revenue is tracked through distinct revenue objects, which have special fields that are used in Amplitude's Event Segmentation and Revenue LTV charts. This allows Amplitude to automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties field.
type RevenueProperties = {
price: number;
productId?: string;
quantity?: number;
revenueType?: string;
receipt?: string;
receiptSignature?: string;
eventProperties?: PropertiesObject;
};
const userProperties = {
price: 100;
productId: "123";
quantity: 2;
revenueType: "productRevenue";
receipt: "11111";
receiptSignature: "signature";
eventProperties: {
"KAY": "VALUE",
"OTHER_KEY": "OTHER_VALUE"
};
}
Amplitude.getInstance().logRevenue(userProperties);
Price can be negative, which may be useful for tracking revenue lost (such as refunds or costs)
Amplitude currently does not support currency conversion. All revenue data should be normalized to a currency of choice before being sent to Amplitude.
Group User Properties
groupIdentify
used for updating properties of particular groups
const identify = new Identify();
identify.set("gender", "female").set("age", 20);
Amplitude.getInstance().groupIdentify("groupType", "groupValue", identify);
User Sessions
A session is a period of time that a user has the app in the foreground. Events that are logged within the same session will have the same session_id. Sessions are handled automatically so you do not have to manually call an API like startSession() or endSession().
Amplitude groups events together by session. A session represents a single period of user activity, with a start and end time. Different SDKs will track sessions differently, depending on the requirements of the platform.
You are able to determine whether to automatically log start and end session events corresponding to the start and end of a user's session.
//Enable automatically log start and end session events
Amplitude.getInstance().trackingSessionEvents(true);
//Disable automatically log start and end session events
Amplitude.getInstance().trackingSessionEvents(false);
Set Custom User ID
If your app has its own login system that you want to track users with, you can call setUserId at any time.
Amplitude.getInstance().setUserId("test_user_id");
Advanced topic
COPPA Control
COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking can be enabled or disabled all at once. Remember that apps asking for information from children under 13 years of age must comply with COPPA.
//Enable COPPA Control
Amplitude.instance().enableCoppaControl();
//Disable COPPA Control
Amplitude.instance().disableCoppaControl();
Opt Out of Tracking
Users may wish to opt out of tracking entirely, which means no events and no records of their browsing history. setOptOut provides a way to fulfill certain users’ requests for privacy.
//Disables instrumentation
Amplitude.getInstance().setOptOut(true);
//Enables instrumentation
Amplitude.getInstance().setOptOut(false);
Dynamic Configuration
React Native SDK allows users to configure their apps to use dynamic configuration. This feature will find the best server url automatically based on app users' geo location.
- If you have your own proxy server and use setServerUrl API, please leave this OFF.
- If you have users in China Mainland, we suggest you turn this on.
- By default, this feature is OFF. So you need to explicitly set it to ON to use it.
- By default, this feature returns server url for Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use setServerZone to set it to EU zone.
Amplitude.getInstance().setUseDynamicConfig(true);
Migration Guide
Our Javascript SDK no longer has support for React Native. If you already have installed the amplitude-js
or the old version of @amplitude/react-native
, please follow the migration guide to implement @amplitude/react-native
v2.
Migration Guide
Troubleshooting
Using an older React Native version and having trouble with iOS? We support versions of React Native >= 0.61.
Here's the process to set up with React Native 0.61
- Swift Setup (XCode):
- Open your
[project-name].xcodeproj
file in XCode - Right click your project name in the file navigator and then click New File, pick swift, it will then prompt you to create a bridging headers file. This is necessary to support swift in RN 0.61.
- Source of this fix: https://stackoverflow.com/a/54586937
- Podfile changes:
- Make sure you are targeting iOS 10 or greater
- Add use_modular_headers! globally to the top of the Podfile
- Disable modular headers for DoubleConversion, Glog and Folly using
:use_modular_headers => false
.
Need Help?
If you have any problems or issues over our SDK, feel free to create a github issue or submit a request on Amplitude Help.
Updated 7 months ago