React Native SDK Integration Guide
Your dedicated account representative will help configure your account for the platforms that you are targeting with your React Native App. They will provide you with both the key and secret for iOS and Android which are required to initialize the SDK and also supply additional resources needed to render the most relevant experiences for your customers.
These instructions require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager. Shopify stores can set up a Rokt placement in seconds using the Rokt Ecommerce app — no coding needed!
1. React Native setup
Add the React Native SDK as a dependency to your application:
npm install react-native-mparticle --save
Import the package into your React Native app code and get an instance of mParticle:
import MParticle from 'react-native-mparticle';
After installing the React Native plugin, continue integrating the Rokt SDK into your mobile app or website by following the steps below. Be sure to include the key and secret provided by your account manager where required or you will see errors in your logs when launching your app or site.
1.1. Add the Rokt SDK to your iOS app
The NPM install step above will automatically include the React framework and the core iOS framework in your project. The Rokt Kit needs to be added as a pod dependency in the ios/Podfile
. However depending on your app and its other dependencies you must integrate it in 1 of 2 ways:
Using CocoaPods, include the Rokt SDK in your application:
CocoaPods
To integrate the Rokt Kit using CocoaPods, specify it in your Podfile with:
pod 'mParticle-Rokt','~> 8.0'
-
Static Libraries are the React Native default, but because the Rokt iOS SDK contains Swift code you need to add an exception for it in the form of a pre-install command in the Podfile.
pre_install do |installer|
installer.pod_targets.each do |pod|
if pod.name == 'mParticle-Apple-SDK' || pod.name == 'mParticle-Rokt' || pod.name == 'Rokt-Widget'
def pod.build_type;
Pod::BuildType.new(:linkage => :dynamic, :packaging => :framework)
end
end
end
endThen run the following command
bundle exec pod install
-
Frameworks are the default for Swift development and while it isn’t preferred by React Native it is supported. Additionally you can define whether the frameworks are built statically or dynamically.
Update your Podfile to be ready to use dynamically linked frameworks by commenting out the following line(if flipper is there)
# :flipper_configuration => flipper_config,
Then run either of the following commands
USE_FRAMEWORKS=static bundle exec pod install
or
USE_FRAMEWORKS=dynamic bundle exec pod install
1.2. Initialize the Rokt SDK
To initialize the SDK, insert the following initialization snippet in your AppDelegate file:
- Make sure to replace
your-key
andyour-secret
with the key and secret provided by your dedicated Rokt team.
- Swift
- Objective-C
import mParticle_Apple_SDK
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development
MParticle.sharedInstance().start(with: options)
return true
}
#import <mParticle_Apple_SDK/mParticle.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize the SDK
MParticleOptions *options = [MParticleOptions optionsWithKey:@"your-key"
secret:@"your-secret"];
// Specify the data environment with environment:
// Set it to MPEnvironmentDevelopment if you are still testing your integration.
// Set it to MPEnvironmentProduction if your integration is ready for production data.
// The default is MPEnvironmentAutoDetect which attempts to detect the environment automatically
options.environment = MPEnvironmentDevelopment;
[[MParticle sharedInstance] startWithOptions:options];
return YES;
}
Further setup
For further help, see the full iOS SDK Integration Guide.
1.1 Add dependencies
The NPM install step above will automatically include the React framework and the core Android library in your project. The Rokt Kit needs to be added as an implementation dependency in the app project. Update your gradle file to include the necessary dependencies for the SDK:
- build.gradle.kts
- build.gradle
dependencies {
implementation("com.mparticle:android-rokt-kit:5.71.0")
}
dependencies {
implementation "com.mparticle:android-rokt-kit:5.71.0"
}
1.2. Initialize the SDK in your app
The Android SDK can be configured using an MParticleOptions
object and a builder class in the onCreate()
of the Application
class. The mParticle Android SDK should be initialized before any other SDK API calls are made.
Make sure to replace your-key
and your-secret
in the above code sample with the key and secret provided by your dedicated Rokt account representative.
- Kotlin
- Java
import com.mparticle.MParticle
import com.mparticle.MParticleOptions
class YourApplicationClass : Application() {
override fun onCreate() {
super.onCreate()
val options: MParticleOptions = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Development) // Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
.build()
MParticle.start(options)
}
}
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;
public class YourApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Production) // Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
.build();
MParticle.start(options);
}
}
Further setup
For more help, see the full Android SDK integration guide.
2. Track User Attributes
You can use the Rokt SDK to collect user attributes separately from events. User attributes are separate from custom attributes when tracking events. The SDK will associate any user attributes collected in a given session with events triggered in the same session.
To collect user attributes, the following code should be run immediately after initializing the Rokt SDK before you log an event.
import MParticle from 'react-native-mparticle';
// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
MParticle.Identity.getCurrentUser((currentUser) => {
if (currentUser) {
console.log('Current user:', currentUser);
currentUser.setUserAttribute('custom-attribute-name', 'custom-attribute-value');
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser.setUserAttribute('firstname', 'John');
currentUser.setUserAttribute('lastname', 'Doe');
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser.setUserAttribute('mobile', '3125551515');
currentUser.setUserAttribute('age', '33');
currentUser.setUserAttribute('gender', 'M');
currentUser.setUserAttribute('city', 'Brooklyn');
currentUser.setUserAttribute('state', 'NY');
currentUser.setUserAttribute('zip', '123456');
currentUser.setUserAttribute('dob', 'yyyymmdd');
currentUser.setUserAttribute('title', 'Mr');
currentUser.setUserAttribute('language', 'en');
currentUser.setUserAttribute('value', '52.25');
currentUser.setUserAttribute('predictedltv', '136.23');
// You can create a user attribute to contain a list of values
const attributeList = [
'documentary',
'comedy',
'romance',
'drama',
];
currentUser.setUserAttributeArray('favorite-genres', attributeList);
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser.removeUserAttribute('attribute-to-remove');
} else {
console.log('No current user found');
}
});
3. Capture Funnel Events
The Rokt SDK allows you to implement event tracking to collect data describing your users' journeys through your app. You can then use this data to optimize your users' experience.
There are three primary event types you can record with the SDK:
- Screen View Events: These are events you can trigger when a screen of your app is loaded.
- Custom Events: These are freeform events you create to track information specific to your app.
- Commerce Events: These are events specific to ecommerce that can describe the different stages of the shopping experience, including adding items to a cart and making a final purchase.
When first integrating with the Rokt SDK, start by implementing screen view tracking. To learn about tracking custom and commerce events, see the Appendix.
Track screen views
One of the most basic event types you can track is the screen view. To log a screen view, call the MParticle.logScreenEvent()
method as soon as the screen loads, passing in the name of the screen as a string and an optional hash map containing any descriptive attributes.
The name you pass in should be one of a limited set of screens, like 'homepage'
or 'product detail page'
.
import MParticle from 'react-native-mparticle';
const screenInfo = {
'rating': '5',
'property_type': 'hotel',
};
MParticle.logScreenEvent('Screen Name', screenInfo);
4. Show a Placement
The main value of the Rokt SDK is unlocked through the selectPlacements
method, which serves a placement (or layout) that is hyper-relevant to your customers based on attributes you provide.
Once the Rokt integration has been initialized, you can call the selectPlacements
method from the page where your layout will be rendered. It should be called as early as possible, and once all required attributes are available, to ensure the best experience for your users.
When calling selectPlacements
you must provide at least the email
, firstname
, lastname
, billingzipcode
and confirmationref
attributes.
import MParticle from 'react-native-mparticle';
const attributes = {
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'mobile': '(555)867-5309',
'postcode': '90210',
'country': 'US'
};
// You may also want to pass optional parameters such as `RoktConfig` which will allow you to customize the placement UI, primarily on whether or not the app is in dark or light mode. Additional optional parameters such as embedded views and events are shown lower.
const roktConfig = MParticle.Rokt.createRoktConfig(
'dark',
MParticle.Rokt.createCacheConfig(20, attributes),
);
MParticle.Rokt.selectPlacements(
'RoktExperience', // identifier - string
attributes, // attributes - map
{}, // placeholders (see below) - map
roktConfig, // configurations - object
);
Optional functions
Embedded placements
Embedded placements share all of the same recommendations and requirements as overlay placements above but allow you to embed the placement views in your UI.
import React, { ComponentRef } from 'react';
import { findNodeHandle } from 'react-native';
import MParticle, { RoktLayoutView } from 'react-native-mparticle';
const placeholder1 = React.createRef<ComponentRef<typeof RoktLayoutView>>();
const showRoktLayout = () => {
const placeholders = {
Location1: findNodeHandle(placeholder1.current),
};
MParticle.Rokt.selectPlacements(
'RoktEmbeddedExperience', // identifier - string
attributes, // attributes - map (variable from above example)
placeholders, // placeholder - map
);
};
// Integrate the `RoktLayoutView` in view hierarchy
<RoktLayoutView ref={placeholder1} placeholderName="Location1" />
Events
The SDK also provides the events through NativeEventEmitter
mechanism.
import { NativeEventEmitter } from 'react-native';
const eventManagerEmitter = new NativeEventEmitter(MParticle.RoktEventManager);
eventManagerEmitter.addListener('RoktEvents', data => {
console.log(`event received ${JSON.stringify(data)}`);
});
Event | Description | Params |
---|---|---|
ShowLoadingIndicator | Triggered before the SDK calls the Rokt backend | |
HideLoadingIndicator | Triggered when the SDK receives a success or failure from the Rokt backend | |
OfferEngagement | Triggered when the user engages with the offer | placementId: String |
PositiveEngagement | Triggered when the user positively engages with the offer | placementId: String |
FirstPositiveEngagement | Triggered when the user positively engages with the offer for the first time | placementId: String |
PlacementInteractive | Triggered when a placement has been rendered and is interactable | placementId: String |
PlacementReady | Triggered when a placement is ready to display but has not rendered content yet | placementId: String |
PlacementClosed | Triggered when a placement is closed by the user | placementId: String |
PlacementCompleted | Triggered when the offer progression reaches the end and no more offers are available to display. Also triggered when cache is hit but the retrieved placement will not be displayed as it has previously been dismissed | placementId: String |
PlacementFailure | Triggered when a placement could not be displayed due to some failure or when no placements are available to show | placementId: String (optional) |
OpenUrl | Triggered when the user presses a URL that is configured to be sent to the partner app | placementId: String, url: String |
CartItemInstantPurchase | Triggered when the catalog item purchase is initiated by the user | placementId: String, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String, totalPrice: number, quantity: number, unitPrice: number |
Appendix
Using App Configurations
Applications can now pass the configuration settings from their own application environment. This allows Rokt SDK to use application's custom configurations instead of relying solely on system defaults.
ColorMode object
Value | Description |
---|---|
light | Application is in Light Mode |
dark | Application is in Dark Mode |
system | Application defaults to System Color Mode |
CacheConfig object
Parameter | Description |
---|---|
cacheDuration | Optional duration in seconds for which the Rokt SDK should cache the experience. Maximum allowed value is 90 minutes and the default (if value is not provided or invalid) is 90 minutes. |
cacheAttributes | Optional attributes to be used as cache key. If null, all the attributes sent in selectPlacements will be used as the cache key. |
const roktConfig = MParticle.Rokt.createRoktConfig(
'dark',
MParticle.Rokt.createCacheConfig(20, attributes),
);
MParticle.Rokt.selectPlacements(
'RoktExperience', // identifier - string
attributes, // attributes - map (variable from above example)
{}, // placeholders - map
roktConfig, // configurations - object
);
Track custom events
After implementing placements and screen view tracking by following the instructions above, you may want to implement additional event tracking.
You can define and track custom events by using the MParticle.Event
object and passing in the event name, event type, and a map of custom attributes.
The supported custom event types for both Kotlin and Java are:
Navigation
- Track user navigation flows and page transitions within your appLocation
- Record user location-based interactions and movementsSearch
- Capture search queries and search-related user actionsTransaction
- Log financial transactions and purchase-related activitiesUserContent
- Track user-generated content like reviews, comments, or postsUserPreference
- Record user settings, preferences, and customization choicesSocial
- Capture social media interactions and sharing activities
import MParticle from 'react-native-mparticle';
const event = new MParticle.Event()
.setName('Test event')
.setType(MParticle.EventType.Other)
.setInfo({ 'Test key': 'Test value' })
MParticle.logMPEvent(event)
Track commerce events
Tracking a commerce event requires three steps:
- Defining the product or products that are being purchased
- Creating an object to contain a transaction summary
- Logging the event, including your product definition and transaction summary
import MParticle from 'react-native-mparticle';
// 1. Create the products
const customAttributes = {
'ocean-view': 'true',
'balcony': 'false',
};
const product = new MParticle.Product('Double Room - Econ Rate', 'econ-1', 100.00, 4);
// Include the map of custom attributes created above
product.customAttributes = customAttributes;
// 2. Summarize the transaction
const transactionAttributes = new MParticle.TransactionAttributes('12345')
.setRevenue(430.00)
.setTax(30.00);
// 3. Log the purchase event
const commerceEvent = MParticle.CommerceEvent.createProductActionEvent(MParticle.ProductActionType.Purchase, [product], transactionAttributes);
// Optional custom attributes for the purchase event can be added as a map of key/value string pairs
commerceEvent.customAttributes = {'sale': 'true', 'phone-booking': 'true'};
MParticle.logCommerceEvent(commerceEvent);