Install Gainsight PX React Native
This article explains how developers can use the Gainsight PX React Native code in their React Native application.
Overview
Gainsight PX can effectively monitor your application, track usage data, provide real-time analytics, and display engagement analytics.
You can use Gainsight PX React Native in your mobile application development. This codebase is platform-independent and works with Android and iOS Operating systems. You can ingest the Gainsight PX code into any mobile application which is developed using the React Native programming language.
Prerequisite
To use Gainsight PX in your application, you must first download and install React Native. For more information on how to install React Native, refer to the Environment Setup article.
Download and Install Gainsight PX
To install Gainsight PX, you can either use the version on the NPM server, or the one on Github.
NPM
npm i @gainsight-px/react-native-gainsight-px
Github
Refer https://github.com/Gainsight/px-react-native-sdk
"dependencies": { ..., ..., "@gainsight-px/react-native-gainsight-px": "https://github.com/Gainsight/px-react-native-sdk.git" }
OR
npm install https://github.com/Gainsight/px-react-native-sdk.git --save
Expo
Run the expo command as directed after installing the package using the npm command.
npx expo run:ios
npx expo run:android
Building on EAS (Expo Application Service)
If there are problem building the apps on EAS or even locally, please add the following to your package.json file:
"expo": { "autolinking": { "exclude": ["@gainsight-px/react-native-gainsight-px"] } }
Integrate Gainsight PX Editor
Gainsight PX Mobile Editor helps you manage PX engagements and Product Mapper from your mobile application.
The In-app Editor allows you to:
- Preview engagements in the mobile app
- View the Product Tree
- Create, edit and delete Module/Features
- Add Tap Rules for Module/Features
To use the in-app editor, copy the Scheme to integrate your mobile application with the your platforms that Gainsight supports.
You can activate the editor using deep linking and forwarding the link to the SDK. While forwarding the information, you as a developer have the ability to implement your own logic and permissions before launching the editor.
This integration is supported by all deep linking plugins. However, the procedure is subject to the dependencies as stated here.
Android
To perform the integration, add the following to your android/app/src/main/AndroidManifest.xml file, in the activity object:
<intent-filter> <data android:scheme="{SCHEME}" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
iOS
Perform the following steps:
-
Navigate to your iOS/ folder.
-
Select the required option from the approaches available to add an editor scheme to the iOS project, as shown in the image below.
You can also use the below mentioned alternative methods:
-
Use the Xcode Project settings:
-
Open the project(Real.xcworkspace) in the iOS folder using Xcode.
-
From the project settings, select the Info tab.
-
Add a new URL item by choosing Add items under URL Types.
-
Add {SCHEME} to URL Schemes.
-
-
Info.plist using Xcode:
-
Open Info.plist using Xcode.
-
Add URL Types to plist file.
-
Add {SCHEME} for URL Schemes items.
-
-
Open Info.plist as TextEdit:
-
Add the following code snippet in the file:
-
<array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>{APP_BUNDLE_ID}</string> <key>CFBundleURLSchemes</key> <array> <string>{SCHEME}</string> </array> </dict> </array>
On React Native application
Perform the following integration steps:
After initialising Gainsight, in componentDidMountState of the App.js, implement `getInitialURL` callback.
A sample implementation using Linking is given below:
componentDidMount() { //Initialise GainsightPX If (Platform.OS == “ios”) { Linking.addEventListener(“url”, this.handleOpenURL); } Linking.getInitialURL().then( url => { if (url != null) { GainsightPX.getInstance().enterEditing(url); } }); } componentWillUnmount() { Linking.removeEventListener(“url”, this.handleOpenURL); } handleOpenURL = event => { if (event.url != null) { GainsightPX.getInstance().enterEditing(url);} }
After initialising Gainsight, in componentDidMountState of the App.js, listen to the `url` event of the Linking component and remove the listener for `url` on componentWillUnmount.
Using Gainsight PX
This section explains how to get started with Gainsight PX mobile app development. You can customize the default settings as required. For more information, refer to the Gainsight PX Configuration section of this article.
Initialize
Once you install Gainsight PX, you can use it in your application.
Note: The code used in this section is platform-independent and can be used in Android or iOS mobile applications.
To track data with Gainsight PX:
- Insert the following import code in the header section:
import {GainsightPX} from 'react-native-gainsight-px';
- Use the following code to initialize Gainsight PX.
let configurations = new Configurations("<API KEY>") configurations.enableLogs = true GainsightPX.getInstance().initialize(configurations) .then(() => { console.log("GainsightPX is initialized"); }) .catch((error) => { console.log(error.status); })
Note: You must use the initialization code only once in your entire application. (We recommend using this code at the beginning of the app)
ExceptionCallback
This section explains how to handle exceptions in the SDK, if any. All the Gainsight PX methods return a Promise<GainsightPXCallBack>. The exceptions are passed into catch as error using GainsightPXCallback interface.
The properties of GainsightPXCallback are as follows:
export interface GainsightPXCallback { status: GainsightPXCallbackStatus; methodName?: string; params?: object; exceptionMessage?: string; } export enum GainsightPXCallbackStatus { FAILURE = 0, SUCCESS = 1 }
- The status property informs if the created event is success/failure.
- The methodName property informs about the invoked function name.
- The params object gives the event properties that were sent to create an event.
- The exceptionMessage informs about the exception that occurred.
Create Events
Events are actions associated with your application and allow you to track various actions performed by users in your app. This section explains how to create events that can track data from your mobile application.
Screen Events
This section explains how to create events that can track data from your mobile application. Events are actions associated with your app and allow you to track various actions performed by users in your app. Currently, the Gainsight PX SDK supports four types of events.
You can use the Screen event to track each of your screens visited by the user. The syntax to capture screen events is as follows:
GainsightPX.getInstance().screenEvent("<#screen-name#>", "<#screen-class#>");
You can also create a screen event to just capture the name of the screen and exclude all of the other details.
GainsightPX.getInstance().screen("<#screen-name#>", "<#map#>")
Custom Events
Custom Events are used to track specific actions in your app.
The syntax to track custom events is:
GainsightPX.getInstance().customEventWithProperties(<#custom_event_name#>, <#map#>);
You can also track custom events without any properties. The syntax for this is:
GainsightPX.getInstance().customEvent(<#custom_event_name#>);
Identify Events
These events are used to identify a user or an Account uniquely.
Gainsight PX provides you with the following syntax:
GainsightPX.getInstance().identifyWithUserId(<#user_id#>) GainsightPX.getInstance().identify(<#user#>, <#account#>)
The following line of code can be used to track a user:
var user = new PXUser("<#user_id#>") user.usem = "david@gmail.com"
The list of properties supported for User tracking is given in the table below:
Property | Data type |
ide | String |
usem | String (Email) |
userHash | String |
gender | String |
lastName | String |
firstName | String |
signUpDate | Date |
title | String |
role | String |
subscriptionId | String |
phone | String |
countryCode | String |
countryName | String |
stateCode | String |
stateName | String |
city | String |
street | String |
continent | String |
postalCode | String |
regionName | String |
timezone | String |
longitude | Double |
latitude | Double |
organization | String |
organizationEmployees | String |
organizationRevenue | String |
organizationIndustry | String |
organizationSicCode | String |
organizationDuns | Int |
accountID | String |
firstVisitDate | Date |
score | Int |
sfdcContactId | String |
<AnyKey> | <Value>(All other keys other than default keys will map to `customAttributes`) |
The list of Attributes for Account Object is given in the table below:
Property | Data Type |
name | String |
trackedSubscriptionId | String |
industry | String |
numberOfEmployees | int |
sicCode | String |
website | String |
naicsCode | String |
plan | String |
countryCode | String |
countryName | String |
stateCode | String |
stateName | String |
city | String |
street | String |
continent | String |
postalCode | String |
regionName | String |
timezone | String |
latitude | Double |
longitude | Double |
sfdcId | String |
<AnyKey> | <Value>(All other keys other than default keys will map to `customAttributes`) |
General Methods
This section describes the general methods (functions) of Gainsight PX SDK. There are three general methods:
Method Name | Method | Description |
Flush | GainsightPX.getInstance().flush() | This method sends all events in the queue to the server, by ignoring the scheduled auto flush. Generally, you need not use this method but there could be situations in which you may need to flush out events |
Enable/Disable | GainsightPX.getInstance().enable() GainsightPX.getInstance().disable() |
These methods help you to enable or disable event tracking on your app. When you use the disable method, no event is sent to server. You can use the disable method on data sensitive areas of your app. |
Global Context
Once you create all the required events, you can set events with a global context. You can set a global context with key-value pairs and send them with the payload. Global context can be set on Date, String, Double, and Boolean data types. Global Context data is stored at the memory level and not disk-level. The key-value pairs are sent with the Payloads. If an application is terminated, all the key-value pairs are erased.
The following code snippet can be used to set the global context:
GainsightPX.getInstance().setGlobalContext(<#[String: GlobalContextValue]#>);
The following code snippet can be used to check if the key is available:
GainsightPX.getInstance().hasGlobalContextKey(<#Name of the key#>)
The following code snippet can be used to remove the key:
GainsightPX.getInstance().removeGlobalContextKeys(<#Array Of Keys#>)
EngagementCallBack
Gainsight PX provides the Engagement Callback feature for mobile engagements that you create for mobile applications. This feature helps in receiving a callback for all button actions and URL clicks that the end-user performs on an engagement. Once you receive the callback, you can decide your next action like helping the user to navigate to a new screen, or perform an API call and so on.
Prerequisite
Ensure that you have installed/configured the Gainsight PX Mobile SDK v1.5.1 or above.
To use the Engagement Callback feature, you need to listen to the EngagementCallback event listener.
Example:
import { NativeModules, Platform, NativeEventEmitter, DeviceEventEmitter, } from 'react-native'; const Emitter = Platform.select({ ios: new NativeEventEmitter(NativeModules.RNGainsightPx), android: DeviceEventEmitter, }); this.props.subscription = Emitter.addListener( 'engagementCallBack', this.didRecieveEngagementPayload, ); didRecieveEngagementPayload = args => { if (args != null && args.actionType === 'link') { let text = 'EngagementMetaData:' + ', actionText: ' + args.actionText + ', actionType: ' + args.actionType + ', engagementId: ' + args.engagementId + ', engagementName: ' + args.engagementName + ', scope.screenName: ' + args.scope.screenName.toString() + ', scope.screenClass: ' + args.scope.screenClass.toString() + alert(text); }};
General Properties
The following table describes the properties in the arguments received from the EngagementCallBack event listener :
Property |
Type |
Description |
actionText |
string |
The text of the linked element. |
actionType/ |
string |
Refers to the element that invoked the Engagement Callback. |
engagementName |
string |
Name of the engagement for which the callback is received |
scope |
object |
Mobile screen scope where the engagement is shown. |
engagementId |
string |
ID of the engagement for which the callback is received . |
* actionData - reserved property for future usage; currently functions similar to actionText
* params - reserved property for future usage to send any custom parameters.
Gainsight PX Configurations
This section describes methods, whose configurations can be modified by you during the initialization stage.
Method Call | Default | Description | Override by Server? |
host(PXHost host) | PXHost.us | Setting the data center that Gainsight PX instance will send the events to. | No |
flushQueueSize | 20 | The number of events that are considered to form a batch to be sent to server. Once this limit is reached, PX sends the events to the server even if it's still not the time for that (by the timer) | Yes |
flushInterval | 20 sec | The time interval during which the client checks if there are any new events to send to the server | Yes |
collectDeviceId (this method is applicable only to Android application) | true | Whether or not to collect the device id from the device | No |
enableLogs | False | Which log level should be logged to CatLog. By default, false is logged | No |
trackApplicationLifecycleEvents | true | Should the client auto-track app related events (APP_OPENED, APP_INSTALLED and APP_UPDATED) | No (Server can drop the event based on remote configuration) |
shouldTrackTapEvents | false |
Should the client auto-track tap events Note: Enabling this helps you track only the single tap gestures. |
Yes |
proxy (string) | null | There's an option to send the network requests via proxy (mainly for security reviews) | Yes |
maxQueueSize | 1000 | The maximum number of items to queue before starting to drop old ones. | No |