React Native SDK

This is the official documentation for the Amplitude Analytics React Native SDK.

Compatibility Matrix

The following matrix lists the support for Amplitude React Native SDK version for different versions of React Native and React Native CLI.

@amplitude/react-native react-native Gradle Android Gradle Plugin
>= 2.17.1 >= 0.71 7.5.1+ 7.2.1+
<= 2.17.0 >= 0.61, <= 0.70 3.5.3+ 3.5.3+

Learn more about the Android Gradle Plugin compatibility.

Install the SDK

Run yarn add @amplitude/react-native in your project directory, the same level with package.json.

1yarn add @amplitude/react-native

iOS installation

1cd ios && pod install

Initialize the SDK

Before you can instrument, you must initialize the SDK using the API key for your Amplitude project.

1import * as React from 'react';
2import { Button } from 'react-native';
3import { Amplitude, Identify } from '@amplitude/react-native';
4 
5const ampInstance = Amplitude.getInstance();
6ampInstance.init(AMPLITUDE_API_KEY);
7 
8export function MyApp() {
9 return (
10 <Button
11 title="Log Event"
12 onPress=() => ampInstance.logEvent('BUTTON_CLICKED')
13 />
14 );
15}

Configure the SDK

Amplitude React Native SDK runs on the top of the Amplitude Android Maintenance SDK, Amplitude iOS Maintenance SDK. The following are the ts/js settable config options. For other default configurations:

Name Description Default Value
enableCoppaControl() Enable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. For example, Amplitude.getInstance().enableCoppaControl();. Coppa control is disabled by default.
disableCoppaControl() Disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. For example, Amplitude.getInstance().disableCoppaControl();. Coppa control is disabled by default.
setAdvertisingIdForDeviceId() boolean. Use the Advertising ID on Android if available from Google Play Services. For example, Amplitude.getInstance().setAdvertisingIdForDeviceId();. Please check here for the required module and permission. false
setAppSetIdForDeviceId() boolean. Use the App Set ID (fall back to this useAdvertisingIdForDeviceId is used) for device ID. For example, Amplitude.getInstance().setAppSetIdForDeviceId();. Please check here for the required module and permission. false
setOptOut() boolean. Whether or not enables tracking opt out. If the user wants to opt out of all tracking, use this method to enable opt out for them. Once opt out is enabled, no events will be saved locally or sent to the server. For example, Amplitude.getInstance().setOptOut(true);. false
trackingSessionEvents() boolean. Whether to automatically log start and end session events corresponding to the start and end of a user's session. For example, Amplitude.getInstance().trackingSessionEvents(true);. false
setUseDynamicConfig() boolean. Whether or not dynamically adjust server URL. For example, Amplitude.getInstance().setUseDynamicConfig(true);. false
setMinTimeBetweenSessionsMillis() number. Sets the minimum cutoff time in milliseconds for sessions to be considered distinct. For example, Amplitude.getInstance().setMinTimeBetweenSessionsMillis(600000);. The input parameter is in milliseconds. 5 minutes. 30 minutes if not enable foreground checking on Android.
setServerZone() serverZone: string, updateServerUrl:boolean. serverZone - US or EU. updateServerUrl - Whether or not enable dynamic configuration. Set Amplitude Server Zone, switch to zone related configuration, including dynamic configuration. If updateServerUrl is true, including server url as well. For example, Amplitude.getInstance().setServerZone('EU', true); The serverZone is US, and dynamic configuration is enabled by default.
setServerUrl() string. Set the API endpoint URL that events are sent to. Automatically selected by ServerZone. For example, Amplitude.getInstance().setServerUrl("https://www.your-server-url.com"). https://api2.amplitude.com/
setEventUploadMaxBatchSize() number. Sets event upload max batch size. This controls the maximum number of events sent with each upload request. For example, Amplitude.getInstance().setEventUploadMaxBatchSize(100);. 50 on Android. 100 on iOS.
setEventUploadPeriodMillis() number. Sets event upload period millis. The SDK will attempt to batch upload unsent events every eventUploadPeriodMillis milliseconds, or if the unsent event count exceeds the event upload threshold. The input parameter is in milliseconds. For example, Amplitude.getInstance().setEventUploadPeriodMillis(100000);. 30 Seconds
setEventUploadThreshold() number. Sets event upload threshold. The SDK will attempt to batch upload unsent events every eventUploadPeriodMillis milliseconds, or if the unsent event count exceeds the event upload threshold. For example, Amplitude.getInstance().setEventUploadThreshold(100);. 30
enableLogging() boolean. Only for Android. Whether to enable message logging by the SDK. For example, Amplitude.getInstance().enableLogging(false);. true
setLogLevel() number. 2 - Log.VERBOSE or 3 - Log.DEBUG or 4 - Log.INFO or 5 - Log.WARN or 6 - Log.ERROR or 7 - Log.ASSERT. Only for Android. Sets the logging level. Logging messages will only appear if they are the same severity level or higher than the set log level. Log.INFO
addLogCallback() (error: AmplitudeLogError) => void. Only for Android. Add log callback, it can help read and collect error message from sdk. The call back function like the following format, ({ tag, message }: { tag: string, message: string }) => { //implement your own logic} null

Configure batching behavior

To support high-performance environments, the SDK sends events in batches. Every event logged by the logEvent method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with setEventUploadThreshold and setEventUploadPeriodMillis. By default, the serverUrl will be https://api2.amplitude.com/. This SDK doesn't support batch mode, the batch API endpoint.

1// Events queued in memory will flush when number of events exceed upload threshold
2// Default value is 30
3Amplitude.getInstance().setEventUploadThreshold(100);
4// Events queue will flush every certain milliseconds based on setting
5// Default value is 30 second.
6Amplitude.getInstance().setEventUploadPeriodMillis(100000);

EU data residency

Beginning with version 2.6.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set. The server zone configuration supports dynamic configuration as well.

For earlier versions, you need to configure the serverURL property after initializing the client.

Note

For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU.

1// For versions starting from 2.6.0
2// No need to call setServerUrl for sending data to Amplitude's EU servers
3Amplitude.getInstance().setServerZone('EU');
4// For earlier versions
5Amplitude.getInstance().setServerUrl("https://api.eu.amplitude.com"));

Send basic events

Events represent how users interact with your application. For example, "button clicked" may be an action you want to track.

1Amplitude.getInstance().logEvent('BUTTON_CLICKED');

Send events with properties

Events can also contain properties that give context about the event. For example, "hover time" may be a relevant event property to "button click."

1Amplitude.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

1Amplitude.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.

1import { Identify } from '@amplitude/react-native';

Set a user property

set sets the value of a user property. You can also chain together multiple identify calls.

1const identify = new Identify();
2identify.set("gender", "female").set("age", 20);
3Amplitude.getInstance().identify(identify);

setOnce

setOnce sets the value of a user property once. Later calls using setOnce are ignored.

1const identify1 = new Identify();
2identify1.setOnce("sign_up_date", "2015-08-24");
3Amplitude.getInstance().identify(identify1);
4const identify2 = new Identify();
5identify2.setOnce("sign_up_date", "2015-08-24");
6Amplitude.getInstance().identify(identify2);// is ignored

add

add increments a user property by some numerical value. If the user property doesn't have a value set yet, it will be initialized to 0 before being incremented.

1const identify = new Identify();
2identify.add("karma", 0.123);
3Amplitude.getInstance().identify(identify);

Set 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.

1const userProperties = {
2 "KEY": "VALUE",
3 "OTHER_KEY": "OTHER_VALUE",
4}
5Amplitude.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.

1const colors = ["rose", "gold"];
2const numbers = [4, 5];
3const identify = new Identify();
4identify.set("colors", colors)
5 .append("ab-tests", "campaign_a")
6 .append("existing_list", numbers);
7Amplitude.getInstance().identify(identify);

append

append appends a value or values to a user property array. If the user property doesn't 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's not a list, it will be converted into a list with the new value added.

1const array = ["some_string", 56];
2const identify = new Identify();
3identify.append("ab-tests", "new-user-test")
4Amplitude.getInstance().identify(identify);

preInsert

preInsert insert a value or values to a user property if it doesn't exist in the user property yet. Pre-insert means inserting the value at the beginning of a given list. If the user property doesn't have a value set yet, it will be initialized to an empty list before the new values are pre-inserted. If the user property has an existing value, it will be no operation.

1const array = ["some_string", 56];
2const identify = new Identify();
3identify.preInsert("ab-tests", "new-user-test")
4Amplitude.getInstance().identify(identify);

postInsert

postInsert insert a value or values to a user property if it doesn't exist in the user property yet. Post-insert means inserting the value at the end of a given list. If the user property doesn't have a value set yet, it will be initialized to an empty list before the new values are post-inserted. If the user property has an existing value, it will be no operation.

1const array = ["some_string", 56];
2const identify = new Identify();
3identify.postInsert("ab-tests", "new-user-test")
4Amplitude.getInstance().identify(identify);

Remove user properties

clearUserProperties wipes all the current user's user properties.

This is a permanent action

This action clears all user properties. Amplitude can't sync the user's user property values from before the wipe to any of the user's future events.

1Amplitude.getInstance().clearUserProperties();

remove

remove removes a value or values to a user property if it does exist in the user property. If the item doesn't exist in the user property, nothing happens.

1const array = ["some_string", 56];
2const identify = new Identify();
3identify.remove("ab-tests", "new-user-test")
4 .remove("some_list",array);
5Amplitude.getInstance().identify(identify);

unset

unset unsets and removes a user property.

1const identify = new Identify();
2identify.unset("karma").unset("gender");
3Amplitude.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.

Price can be a negative value, which is useful for tracking lost revenue.

Note

Amplitude doesn't support currency conversion. All revenue data should be normalized to your currency of choice before being sent.

1type RevenueProperties = {
2 price: number;
3 productId?: string;
4 quantity?: number;
5 revenueType?: string;
6 receipt?: string;
7 receiptSignature?: string;
8 eventProperties?: PropertiesObject;
9};
1const userProperties = {
2 price: 100;
3 productId: "123";
4 quantity: 2;
5 revenueType: "productRevenue";
6 receipt: "11111";
7 receiptSignature: "signature";
8 eventProperties: {
9 "KAY": "VALUE",
10 "OTHER_KEY": "OTHER_VALUE"
11 };
12}
13Amplitude.getInstance().logRevenue(userProperties);

Group user properties

Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:

  • Updates affect only future events, and don't update historical events.
  • You can track up to 5 unique group types and 10 total groups.

The groupIdentify method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group.

1const identify = new Identify();
2identify.set("gender", "female").set("age", 20);
3Amplitude.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 have the same session_id.

Sessions are handled automatically so you don't 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 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.

1//Enable automatically log start and end session events
2Amplitude.getInstance().trackingSessionEvents(true);
3//Disable automatically log start and end session events
4Amplitude.getInstance().trackingSessionEvents(false);

Set a custom user ID

If your app has its login system that you want to track users with, you can call setUserId at any time.

1Amplitude.getInstance().setUserId("test_user_id");

Advanced topics

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.

1// Enable COPPA Control
2Amplitude.instance().enableCoppaControl();
3// Disable COPPA Control
4Amplitude.instance().disableCoppaControl();

Opt users 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.

1//Disables instrumentation
2Amplitude.getInstance().setOptOut(true);
3//Enables instrumentation
4Amplitude.getInstance().setOptOut(false);

Dynamic configuration

React Native SDK allows users to configure their apps to use dynamic configuration. This feature finds the best server URL automatically based on app users' location.

  • If you have your own proxy server and use setServerUrl API, don't use dynamic configuration.
  • If you have users in Mainland China, Amplitude recommends that you use dynamic configuration.
  • By default, this feature is off. You must explicitly enable it to use it.
  • By default, this feature returns the server URL of Amplitude's US servers. If you need to send data to Amplitude's EU servers, use setServerZone to set it to EU zone.
1Amplitude.getInstance().setUseDynamicConfig(true);

Troubleshooting

Using an older React Native version and having trouble with iOS?

Amplitude supports versions of React Native >= 0.61. Here's the process to set up with React Native 0.71. See the compatibility matrix for more details.

  1. 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 prompts 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
  2. 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.
Was this page helpful?

Thanks for your feedback!

June 18th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.