LogoLogo
  • Contributing to RudderStack
  • Destination_Name
  • LICENSE
  • RudderStack Docs
  • docs
    • FAQ
    • Identity Resolution
    • Home
    • cloud-extract-sources
      • ActiveCampaign Source
      • Bing Ads
      • Chargebee
      • Common Settings
      • Facebook Ads
      • Freshdesk
      • Google Ads Source
      • Google Analytics
      • Google Search Console
      • Google Sheets
      • Cloud Extract Sources
      • Intercom v2
      • Intercom
      • Mailchimp
      • Marketo
      • Mixpanel
      • NetSuite
      • Pipedrive
      • QuickBooks
      • Salesforce Pardot
      • Sendgrid Source
      • Stripe Source
      • Xero
      • Zendesk Chat
      • Zendesk
      • hubspot
        • HubSpot Data Model and Schema Information
        • HubSpot
      • salesforce
        • Salesforce
        • Schema Comparison: RudderStack vs. Segment
    • connections
      • Connection Modes: Cloud Mode vs. Device Mode
    • data-governance
      • Data Governance
      • RudderTyper
      • Data Governance API
      • RudderTyper
      • tracking-plans
        • Tracking Plans
        • Tracking Plan Spreadsheet
    • data-warehouse-integrations
      • Amazon Redshift
      • Azure Data Lake
      • Azure Synapse
      • ClickHouse
      • Databricks Delta Lake
      • Google Cloud Storage Data Lake
      • Google BigQuery
      • Identity Resolution
      • Warehouse Destinations
      • Microsoft SQL Server
      • PostgreSQL
      • Amazon S3 Data Lake
      • Snowflake
      • FAQ
      • Warehouse Schema
    • destinations
      • Destinations
      • Webhooks
      • advertising
        • Bing Ads
        • Criteo
        • DCM Floodlight
        • Facebook App Events
        • Facebook Custom Audience
        • Facebook Pixel
        • Google Ads (gtag.js)
        • Google AdWords Enhanced Conversions
        • Google Adwords Remarketing Lists (Customer Match)
        • Advertising
        • LinkedIn Insight Tag
        • Lotame
        • Pinterest Tag
        • Reddit Pixel
        • Snap Pixel
        • TikTok Ads
      • analytics
        • Amplitude
        • AWS Personalize
        • Chartbeat
        • Firebase
        • FullStory
        • Google Analytics 360
        • Google Analytics
        • Heap.io
        • Hotjar
        • Analytics
        • Indicative
        • Keen
        • Kissmetrics
        • Kubit
        • Lytics
        • Mixpanel
        • Pendo
        • PostHog
        • Quantum Metric
        • Singular
        • adobe-analytics
          • Adobe Analytics Heartbeat Measurement
          • Mobile Device Mode Settings
          • Web Device Mode Settings
          • E-commerce Events
          • Adobe Analytics
          • Setting Up Adobe Analytics in RudderStack
        • google-analytics-4
          • Cloud Mode
          • Device Mode
          • Google Analytics 4
          • Setting up Google Analytics 4
        • profitwell
          • ProfitWell
          • Cloud Mode
          • Device Mode
      • attribution
        • Adjust
        • AppsFlyer
        • Branch
        • Attribution
        • Kochava
        • TVSquared
      • business-messaging
        • Business Messaging
        • Intercom
        • Kustomer
        • Slack
        • Trengo
      • continuous-integration
        • Visual Studio App Center
        • Continuous Integration
      • crm
        • Delighted
        • HubSpot
        • CRM
        • Salesforce
        • Variance
        • Zendesk
      • customer-data-platform
        • Customer Data Platform
        • Segment
      • error-reporting
        • Bugsnag
        • Error Reporting
        • Sentry
      • marketing
        • ActiveCampaign
        • AdRoll
        • Airship
        • Appcues
        • Autopilot
        • Blueshift
        • Braze
        • CleverTap
        • Customer.io
        • Gainsight PX
        • Gainsight
        • Marketing
        • Iterable
        • Klaviyo
        • Leanplum
        • Mailchimp
        • Marketo Lead Import
        • Marketo
        • MoEngage
        • Ometria
        • Pardot
        • Post Affiliate Pro
        • Qualtrics
        • SendGrid
        • Salesforce Marketing Cloud
        • Userlist
        • drip
          • Cloud Mode
          • Device Mode
          • Drip
          • Setting Up Drip in RudderStack
      • productivity
        • Google Sheets
        • Productivity
      • storage-platforms
        • Amazon S3
        • DigitalOcean Spaces
        • Google Cloud Storage
        • Storage Platforms
        • Azure Blob Storage
        • MinIO
        • Redis
      • streaming-platforms
        • Amazon EventBridge
        • Amazon Kinesis Firehose
        • Amazon Kinesis
        • Azure Event Hubs
        • BigQuery Stream
        • Confluent Cloud
        • Google Pub/Sub
        • Streaming Platforms
        • Apache Kafka
      • tag-managers
        • Google Tag Manager
        • Tag Managers
      • testing-and-personalization
        • Algolia Insights
        • Candu
        • Google Optimize
        • A/B Testing & Personalization
        • LaunchDarkly
        • Monetate
        • Optimizely Full Stack
        • Optimizely Web
        • Split.io
        • Statsig
        • VWO (Visual Website Optimizer)
    • get-started
      • RudderStack Cloud vs. RudderStack Open Source
      • Glossary
      • Get Started
      • RudderStack Architecture
    • reverse-etl
      • Amazon Redshift
      • Amazon S3
      • ClickHouse
      • FAQ
      • Google BigQuery
      • Reverse ETL
      • PostgreSQL
      • Snowflake
      • common-settings
        • Importing Data using Models
        • Importing Data using Tables
        • Common Settings
        • Sync Modes
        • Sync Schedule
      • features
        • Airflow Provider
        • Features
        • Models
        • Visual Data Mapper
    • rudderstack-api
      • Data Regulation API
      • HTTP API
      • RudderStack API
      • Personal Access Tokens
      • Pixel API
      • Test API
      • api-specification
        • Application Lifecycle Events Specification
        • API Specification
        • Video Events Specification
        • rudderstack-ecommerce-events-specification
          • Browsing
          • Coupons
          • E-Commerce Events Specification
          • Ordering
          • Promotions
          • Reviewing
          • Sharing
          • Wishlist
        • rudderstack-spec
          • Alias
          • Common Fields
          • Group
          • Identify
          • RudderStack Event Specification
          • Page
          • Screen
          • Track
    • rudderstack-cloud
      • Audit Logs
      • Dashboard Overview
      • Destinations
      • RudderStack Cloud
      • Live Events
      • Connection Modes: Cloud Mode vs. Device Mode
      • Sources
      • Teammates (User Management)
      • connections
        • Adding a Destination
        • Connections
    • rudderstack-open-source
      • Control Plane Setup
      • RudderStack Open Source
      • installing-and-setting-up-rudderstack
        • Developer Machine Setup
        • Docker
        • Data Plane Setup
        • Kubernetes
        • Sending Test Events
    • stream-sources
      • App Center
      • AppsFlyer
      • Auth0
      • Braze
      • Customer.io
      • Extole
      • Event Stream Sources
      • Iterable
      • Looker
      • PostHog
      • Segment
      • Shopify
      • Webhook Source
      • rudderstack-sdk-integration-guides
        • Client-side Event Filtering
        • SDKs
        • AMP Analytics
        • Cordova
        • .NET
        • Go
        • Java
        • Node.js
        • PHP
        • Python
        • React Native
        • Ruby
        • Rust
        • Unity
        • SDK FAQs
        • rudderstack-android-sdk
          • Adding Application Class
          • Flushing Events Periodically
          • Android
        • rudderstack-flutter-sdk
          • Flutter SDK v1
          • Flutter v2
          • Flutter
        • rudderstack-ios-sdk
          • iOS
          • tvOS
          • watchOS
        • rudderstack-javascript-sdk
          • Data Storage in Cookies
          • Detecting Ad-blocked Pages
          • JavaScript
          • JavaScript SDK Enhancements
          • JavaScript SDK FAQs
          • Querystring API
          • Quick Start Guide
          • Version Migration Guide
          • consent-managers
            • Consent Managers
            • OneTrust
    • transformations
      • Access Token
      • FAQ
      • Transformations
      • Transformations API
    • user-guides
      • User Guides
      • administrators-guide
        • Troubleshooting Guide
        • Alerting Guide
        • Bucket Configuration Settings for Event Backups
        • Configuration Parameters
        • Event Replay
        • High Availability
        • Horizontal Scaling
        • Administrator's Guides
        • Infrastructure Provisioning
        • Monitoring and Metrics
        • Okta SSO Setup
        • OneLogin SSO Setup
        • RudderStack Grafana Dashboard
        • Software Releases
      • how-to-guides
        • How to Use Custom Domains
        • How to Develop Integrations for RudderStack
        • How to Configure a Destination via the Event Payload
        • How to Filter Events using Different Methods
        • How to Filter Selective Destinations
        • How to Submit a Pull Request for a New Integration
        • How-to Guides
        • How to Debug Live Destination Events
        • How to Use AWS Lambda Functions with RudderStack
        • create-a-new-destination-transformer-for-rudder
          • Best Practices for Coding Transformation Functions in JavaScript
          • How to Create a New Destination Transformation for RudderStack
        • implement-native-js-sdk-integration
          • How to Add a Device Mode SDK to RudderStack JavaScript SDK
          • How to Implement a Native JavaScript SDK Integration
        • rudderstack-jamstack-integration
          • How to Integrate RudderStack with Your JAMstack Site
          • How to Integrate Rudderstack with Your Angular App
          • How to Integrate Rudderstack with Your Astro Site
          • How to Integrate Rudderstack with Your Eleventy Site
          • How to Integrate Rudderstack with Your Ember.js App
          • How to Integrate Rudderstack with a Gatsby Website
          • How to Integrate Rudderstack with a Hugo Site
          • How to Integrate Rudderstack with Your Jekyll Site
          • How to Integrate Rudderstack with Your Next.js App
          • How to Integrate Rudderstack with Your Nuxt.js App
          • How to Integrate Rudderstack with Your Svelte App
          • How to Integrate Rudderstack with Your Vue App
      • migration-guides
        • Migrating from Blendo to RudderStack
        • Migrating Your Warehouse Destination from Segment to RudderStack
        • Migration Guides
        • Migrating from Segment to RudderStack
  • src
    • @rocketseat
      • gatsby-theme-docs
        • text
          • Home
Powered by GitBook
On this page
  • SDK setup requirements
  • Installing the React Native SDK
  • Initializing the RudderStack client
  • Configuring your RudderStack client
  • Identify
  • Track
  • Screen
  • Automatic screen recording
  • Group
  • Alias
  • Reset
  • Enabling/disabling user tracking via the optOut API (GDPR support)
  • Registering callbacks
  • Filtering events
  • Enabling/disabling events for specific destinations
  • 1. Passing destinations while initializing the SDK
  • 2. Passing destinations while making event calls
  • External ID
  • Debugging
  • Setting the advertisement ID
  • Anonymous ID
  • FAQs
  • Do I need to link the SDK using the React Native link?
  • Can I use the SDK with a React Native application created with Expo?
  • What is the need to use the await keyword?
  • Does the Android build fail after adding the SDK to your Application?
  • How do I get the user traits after making an identify call?
  • Contact us

Was this helpful?

  1. docs
  2. stream-sources
  3. rudderstack-sdk-integration-guides

React Native

Detailed technical documentation on RudderStack’s React Native SDK to send events from your React Native application to various destinations.

PreviousPythonNextRuby

Last updated 3 years ago

Was this helpful?

The RudderStack React Native SDK allows you to track event data from your React Native applications and send it to your specified destinations via RudderStack.

You can check the to get a more hands-on understanding of the SDK.

SDK setup requirements

To set up the RudderStack React Native SDK, the following prerequisites must be met:

  • You will need to set up a .

  • Once signed up, set up a React Native source in the dashboard. For more information, follow . You should then see a Write Key for this source, as shown below:

  • You will also need a data plane URL. Follow for more information on the data plane URL and where to get it.

  • We also recommend setting up the on your system.

Installing the React Native SDK

The recommended way to install the React Native SDK is through .

To add the SDK as a dependency, perform the following steps:

  • Go to the root of your application and add @rudderstack/rudder-sdk-react-native as a dependency as shown:

npm yarn

npm install @rudderstack/rudder-sdk-react-native --save
yarn add @rudderstack/rudder-sdk-react-native
  • Navigate to your Application's iOS folder and install all the required pods with:

pod install

Initializing the RudderStack client

After adding the SDK as a dependency, you need to set up the SDK.

  • Make sure you import the SDK as shown:

import rudderClient from "@rudderstack/rudder-sdk-react-native"
  • Add the following code in your application:

await rudderClient.setup(WRITE_KEY, {
  dataPlaneUrl: DATA_PLANE_URL,
  trackLifecycleEvents: true,
  recordScreenViews: true,
})

We highly recommend using the await keyword with the setup call.

The setup method has the following signature:

Name
Data Type
Required
Description

writeKey

String

Yes

Your React Native source write key

configuration

Object

No

Contains the RudderStack client configuration

Configuring your RudderStack client

You can configure your client based on the following parameters by passing them in the configuration object of your setup call.

Parameter
Type
Description
Default value

logLevel

int

Controls how much of the log you want to see from the SDK.

RUDDER_LOG_LEVEL.ERROR

dataPlaneUrl

string

URL of your data-plane. Please refer above to see how to fetch the data plane URL.

https://hosted.rudderlabs.com

flushQueueSize

int

Number of events in a batch request to the server.

30

dbThresholdCount

int

The number of events to be saved in the SQLite database. Once the limit is reached, older events are deleted from the DB.

10000

sleepTimeout

int

Minimum waiting time to flush the events to the server.

10 seconds

configRefreshInterval

int

It will fetch the config from dashboard after this many hours.

2

trackLifecycleEvents

boolean

Whether SDK will capture application life cycle events automatically.

true

autoCollectAdvertId

Boolean

Determines if the SDK will collect the advertisement ID.

false

recordScreenViews

boolean

Whether SDK will capture screen view events automatically.

false

controlPlaneUrl

string

https://api.rudderlabs.com

Identify

RudderStack captures the deviceId and uses it as the anonymousId for identifying the user. This helps in tracking the users across the application installation. To attach more information to the user, you can use the identify method. Once you set the identify information to the user, the SDK persists the user information and passes it to the subsequent track or screen calls. To reset the user identification, you can use the reset method.

A sample identify event is as shown:

rudderClient.identify(
  "test_userId",
  {
    email: "testuser@example.com",
    location: "UK",
  },
  null
)

The identify method has the following signature:

Name
Data Type
Required
Description

userId

String

Yes

The user's unique identifier

traits

Object

No

Traits information for the user

option

Object

No

Extra options for the identify event

Track

You can record the user activity through the track method. Every user action is called an event.

A sample track event is shown below:

rudderClient.track("test_track_event", {
  test_key_1: "test_value_1",
  test_key_2: {
    test_child_key_1: "test_child_value_1",
  },
})

The track method has the following signature:

Name
Data Type
Required
Description

name

String

Yes

Name of the tracked event

property

Object

No

Extra data properties to send along with the event

options

Object

No

Extra event options

RudderStack automatically tracks the following optional events:

  1. Application Installed

  2. Application Updated

  3. Application Opened

  4. Application Backgrounded

You can disable these events by passing trackLifecycleEvents as false in the configuration object. However, we recommend keeping them enabled.

Screen

You can use the screen call to record whenever the user sees a screen on the mobile device. You can also send some extra properties along with this event.

An example of the screen event is as shown:

rudderClient.screen("Main Activity", {
  foo: "bar",
})

Alternatively, you can use the following method signature:

Name
Data Type
Required
Description

screenName

String

Yes

Name of the screen viewed by the user.

property

Object

No

Extra property object to pass along with the screen call.

option

Object

No

Extra options passed along with screen event.

Automatic screen recording

You can enable the automatic recording of screen views by passing recordScreenViews as true while initializing the rudderClient. This automatically sends a screen call for every screen that a user views. By default, recordScreenViews is set to false.

To track the screen views of the React Native Screens, you can use the following code snippet:

import rudderClient from "@rudderstack/rudder-sdk-react-native"
import {
  NavigationContainer
} from '@react-navigation/native';

const App = () => {
  const routeNameRef = React.useRef();
  const navigationRef = React.useRef();
  return ( <
    NavigationContainer ref = {
      navigationRef
    }
    onReady = {
      () => {
        routeNameRef.current = navigationRef.current.getCurrentRoute().name;
      }
    }
    onStateChange = {
      async () => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName = navigationRef.current.getCurrentRoute().name;

        if (previousRouteName !== currentRouteName) {
          rudderClient.screen(currentRouteName);
        }
        routeNameRef.current = currentRouteName;
      }
    } >
    ...
    <
    /NavigationContainer>
  );
};

export default App;

Group

RudderStack's group method lets you link an identified user with a group, such as a company, organization, or an account. You can also record any traits associated with the group like the company name, number of employees, etc.

A sample group call is shown below:

rudderClient.group("company123", {
  "city": "New Orleans",
  "state": "Louisiana",
  "country": "USA"
})

The group call has the following method signature:

Name
Data Type
Required
Description

groupId

String

Yes

Your group's unique identifier

traits

Object

No

The group's traits

option

Object

No

Extra options passed along with group event.

Alias

The alias call lets you merge different identities of a known user.

alias is an advanced method that lets you change the tracked user's ID explicitly. This method is useful when managing identities for some of the downstream destinations.

A sample alias call is as shown:

rudderClient.alias("newId")

The alias call has the following method signature:

Name
Data Type
Required
Description

newId

String

Yes

The new identifier you want to assign to the user.

option

Object

No

Extra options passed along with alias event.

Reset

You can use the reset method to clear the persisted traits for the identify call. This is required for Logout operations.

await rudderClient.reset()

It is highly recommended to use the await keyword with the reset call.

Enabling/disabling user tracking via the optOut API (GDPR support)

RudderStack gives the users (e.g., an EU user) the ability to opt out of tracking any user activity until the user gives their consent. You can do this by leveraging RudderStack's optOut API.

The optOut API takes true or false as a Boolean value to enable or disable tracking user activities. This flag persists across device reboots.

The following snippet highlights the use of the optOut API to disable user tracking:

await rudderClient.optOut(true)

Once the user grants their consent, you can enable user tracking once again by using the optOut API with false as a parameter sent to it, as shown:

await rudderClient.optOut(false)

The optOut API is available in the React Native SDK starting from version 1.0.14.

Registering callbacks

The React Native SDK lets you trigger a callback once any device-mode integration is successful. You can use this callback to perform any operation that you wanted to do once a device-integration is successful.

An example of registering a callback for App Center is as shown:

await rc.registerCallback("App Center", () => {
  console.log("App Center is ready")
})

The registerCallback method has the following signatures:

Name
Data Type
Required
Description

destinationName

string

Yes

Display name of the device-mode destination.

callback

Function

Yes

Callback function to be triggered once device-mode integration is successful.

Filtering events

Enabling/disabling events for specific destinations

The React Native SDK lets you enable or disable sending events to a specific destination or all the destinations to which the source is connected. You can specify these destinations by creating an object as shown:

const options = {
  integrations: {
    // default value for `All` is true
    All: false,
    // specifying destination by its display name
    Amplitude: true,
    Mixpanel: false,
  },
}

The keyword All in the above snippet represents all the destinations the source is connected to. Its value is set to true by default.

There are two methods in which you can pass the destinations specified in the above snippet to the SDK:

1. Passing destinations while initializing the SDK

This is helpful when you want to enable or disable sending the events across all the event calls made using the SDK to the specified destinations.

rudderClient.setup(WRITE_KEY, config, options)

2. Passing destinations while making event calls

This approach is helpful when you want to enable or disable sending only a particular event to the specified destinations, or if you want to override the specified destinations passed with the SDK initialization (as described in the method above) for a particular event.

rudderClient.track(
  "test_track_event",
  {
    test_key_1: "test_value_1",
  },
  options
)

If you specify the destinations both while initializing the SDK as well as while making an event call, then the destinations specified at the event level only will be considered.

External ID

You can pass your custom userId along with standard userId in your identify calls. We add those values under context.externalId. The following code snippet shows a way to add externalId to your identify request.

const options = {
  externalIds: [
    {
      id: "some_external_id_1",
      type: "brazeExternalId",
    },
  ],
}
rudderClient.identify(
  "test_userId",
  {
    email: "testuser@example.com",
    location: "UK",
  },
  options
)

Debugging

If you run into any issues regarding the RudderStack React Native SDK, you can turn on the VERBOSE or DEBUG logging to find out what the issue is.

First, make sure you modify your import statement to include RUDDER_LOG_LEVEL with:

import rudderClient, {
  RUDDER_LOG_LEVEL,
} from "@rudderstack/rudder-sdk-react-native"

Then to turn on the logging, change your RudderClient initialization to the following:

await rudderClient.setup(WRITE_KEY, {
  dataPlaneUrl: DATA_PLANE_URL,
  logLevel: RUDDER_LOG_LEVEL.DEBUG, // or VERBOSE
})

You can set the log level to one of the following values:

  1. NONE

  2. ERROR

  3. WARN

  4. INFO

  5. DEBUG

  6. VERBOSE

Setting the advertisement ID

await rudderClient.setup(WRITE_KEY, {
  dataPlaneUrl: DATA_PLANE_URL,
  trackLifecycleEvents: true,
  autoCollectAdvertId: true,
  recordScreenViews: true,
})

You can use the putAdvertisingId method to pass your Android and iOS AAID and IDFA respectively. The putAdvertisingId method accepts two string arguments :

  • androidId : Your Android advertisingId (AAID)

  • iOSId : Your iOS advertisingId (IDFA)

A sample snippet highlighting the use of putAdvertisingId is shown below:

rudderClient.putAdvertisingId(AAID, IDFA)

On iOS, you need to call the putAdvertisingId method before calling setup().

Anonymous ID

You can use the putAnonymousId method to pass your anonymousId and the SDK will use that instead of the deviceId. The putAnonymousId method accepts one string argument:

  • id: The user's anonymousId.

An example of this method's usage is as shown:

rudderClient.putAnonymousId(ANONYMOUS_ID)

FAQs

Do I need to link the SDK using the React Native link?

No, you don't need to link the SDK as it is auto-linked. If you have linked it using react-native link and are facing any issues, use react-native unlink rudder-sdk-react-native to unlink it.

Can I use the SDK with a React Native application created with Expo?

What is the need to use the await keyword?

The functions exposed by the SDK are asynchronous in nature. If you want a synchronous behavior, you must use the await keyword. We highly recommend using the await keyword with the setup call to make sure that the SDK has been properly set up, before any further calls are made.

Does the Android build fail after adding the SDK to your Application?

Please try using Android Studio to build your application. This should fix most of the errors.

How do I get the user traits after making an identify call?

You can get the user traits after making an identify call as shown:

const rudderContext = await rc.getRudderContext()
console.log("Traits are : " + JSON.stringify(rudderContext.traits))

Contact us

Check the section below for a full list of configurable parameters.

Refer to the section to get a list of all supported values.

If you are using our open-source utility, use this option to point to your hosted sourceConfig. SDK will add /sourceConfig along with this URL

The recordScreenViews parameter records the screen views of the native Android or the iOS only and not by the React Native Views.

When sending events to a destination via the , you can explicitly specify which events should be discarded or allowed to flow through - by whitelisting or blacklisting them.

Refer to the guide for more information on this feature.

Make sure the destination names that you pass while specifying the destinations should exactly match the names listed .

RudderStack collects the advertisement ID only if autoCollectAdvertId is set to true during the , as shown:

No. The SDK is a React Native module, and currently, the expo doesn't support adding native modules. You can still your Expo application and use the RudderStack and SDKs.

For queries on any of the sections covered in this guide, you can or start a conversation in our community.

If you come across any issues while using the React Native SDK, you can open a new issue on our .

Activities
Views
device mode
Client-side Event Filtering
here
eject
Android
iOS
contact us
Slack
GitHub Issues page
Configuring your RudderStack client
SDK initialization
Control Plane Lite
Debugging
GitHub codebase
RudderStack account
this guide
this section
React Native development environment
npm
Github Badge
React Native source write key