React Native wrapper to bridge our iOS and Android SDK
🏠 Website
📂 Homepage
$ npm install @intercom/intercom-react-nativeor
yarn add @intercom/intercom-react-nativeIf you're using React Native v0.60 or above, the library will be linked automatically without any steps being taken.
$ react-native link @intercom/intercom-react-native
- Add below code to
android/settings.gradle
include ':intercom-react-native'
project(':intercom-react-native').projectDir =newFile(rootProject.projectDir, '../node_modules/@intercom/intercom-react-native/android')- Then edit
android/app/build.gradle, insidedependenciesat very bottom add
implementation project(':intercom-react-native')- Add below lines to
android/app/src/main/java/com/YOUR_APP/app/MainApplication.javainsideonCreatemethod, replacingapiKeyandappIdwhich can be found in your workspace settings.
importcom.intercom.reactnative.IntercomModule; // <-- Add this line// ...@OverridepublicvoidonCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */false);
// ...IntercomModule.initialize(this, "apiKey", "appId"); // <-- Add this line// ...
}- Open
android/build.gradleand changeminSdkVersionto 21,compileSdkVersionandtargetSdkVersionto at least 31
buildscript {
// ...
ext {
buildToolsVersion ="29.0.2"
minSdkVersion =21// <-- Here
compileSdkVersion =31// <-- Here
targetSdkVersion =31// <-- Here
}
// ...
}- In
android/build.gradlemake sure thatcom.android.tools.build:gradleversion is greater than4.0.0
dependencies {
classpath("com.android.tools.build:gradle:4.0.1")
// ...
}You will need to include the READ_EXTERNAL_STORAGE permission in android/app/src/main/AndroidManifest.xml if you have enabled attachments:
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>You can also include VIBRATE to enable vibration in push notifications:
<uses-permissionandroid:name="android.permission.VIBRATE"/>For Push notification support add GoogleServices and Firebase Cloud Messagng to your app.
More information about push notification setup HERE
- Inside
android/build.gradleadd
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:4.2.0'// <-- Add this
}
}- In
android/app/build.gradlein dependencies addFirebase Messagingand at the very bottom applyGoogle Services Plugin:
// ...dependencies{
implementation "com.facebook.react:react-native:+"
implementation 'com.google.firebase:firebase-messaging:20.2.+'// <-- Add this// ...
}
// ...
apply plugin: 'com.google.gms.google-services'// <-- Add this
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)Place
google-services.jsoninandroid/appdirectory.Create
MainNotificationService.javainside your app directory(com.example.app) with below content:Remember to replace
package com.example.app;, with your app package name
packagecom.example.app;
importcom.google.firebase.messaging.FirebaseMessagingService;
importcom.google.firebase.messaging.RemoteMessage;
importcom.intercom.reactnative.IntercomModule;
publicclassMainNotificationServiceextendsFirebaseMessagingService {
@OverridepublicvoidonNewToken(StringrefreshedToken) {
IntercomModule.sendTokenToIntercom(getApplication(), refreshedToken);
//DO LOGIC HERE
}
publicvoidonMessageReceived(RemoteMessageremoteMessage) {
if (IntercomModule.isIntercomPush(remoteMessage)) {
IntercomModule.handleRemotePushMessage(getApplication(), remoteMessage);
} else {
// HANDLE NON-INTERCOM MESSAGE
}
}
}- Edit
AndroidManifest.xml. Add below content inside<application>below<activity/>
Make sure that xmlns:tools="http://schemas.android.com/tools" is added to manifest tag
<!-- Add xmlns:tools to manifest. See example below-->
<manifestxmlns:tools="http://schemas.android.com/tools"
>
<application>
<activity>
...
</activity>
...
<!-- START: Add this-->
<serviceandroid:name=".MainNotificationService">
<intent-filter>
<actionandroid:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<receiverandroid:name="com.intercom.reactnative.RNIntercomPushBroadcastReceiver"tools:replace="android:exported"android:exported="true"/>
<!-- END: Add this-->
</application>
</manifest>- Add below code to your React Native app
useEffect(()=>{/** * Handle PushNotification */constappStateListener=AppState.addEventListener('change',(nextAppState)=>nextAppState==='active'&&Intercom.handlePushMessage());return()=>AppState.removeEventListener('change',()=>true);// <- for RN < 0.65return()=>appStateListener.remove()// <- for RN >= 0.65},[])- Add below code to
<activity>insideAndroidManifest.xml
<activityandroid:name=".MainActivity"android:label="@string/app_name"android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"android:launchMode="singleTask"android:windowSoftInputMode="adjustResize">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<!-- START: Add this -->
<intent-filter>
<actionandroid:name="android.intent.action.VIEW"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<categoryandroid:name="android.intent.category.BROWSABLE"/>
<dataandroid:scheme="http"android:host="Your app url(www.app.com)"/> <!-- Edit this line -->
<dataandroid:scheme="Your app scheme(app)"/> <!-- Edit this line -->
</intent-filter>
<!-- END: Add this -->
</activity>
See the example app for an example of how to handle deep linking in your app.
cd ios
pod install
cd ..If you're using React Native v0.60 or above, the library will be linked automatically without any steps being taken.
See How to manually link IOS Intercom SDK
Open
ios/AppDelegate.mthen add below code:At the top of file add the following:
#import"AppDelegate.h"
#import<React/RCTBridge.h>
#import<React/RCTBundleURLProvider.h>
#import<React/RCTRootView.h>// ...
#import<IntercomModule.h>// <-- Add This- Inside
didFinishLaunchingWithOptionsbeforereturn YESadd, remember to replaceapiKeyandappIdwhich can be found in your workspace settings:
// ...
self.window.rootViewController = rootViewController;
[IntercomModule initialize:@"apiKey"withAppId:@"appId"]; // <-- Add this (Remember to replace strings with your api keys)returnYES;
}Add this permission to your Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>Send photos to support center</string>Add Push Notifications and Background Modes > Remote NotificationsDetails HERE
Option 1: In your JavaScript code
An example using react-native-notifications:
// Request notification permissionsNotifications.registerRemoteNotifications();// When permission is granted, send the device token to Intercom using [Intercom.sendTokenToIntercom(token)](#intercomsendtokentointercomtoken)Notifications.events().registerRemoteNotificationsRegistered(({ deviceToken }: Registered)=>{Intercom.sendTokenToIntercom(deviceToken);});Option 2: In your native code
- In
AppDelegate.mat the top add
#import<UserNotifications/UserNotifications.h>- Request notification permissions when app launches by adding the following to
didFinishLaunchingWithOptionsbeforereturn YES;:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...// START: Code to addUNUserNotificationCenter *center = [UNUserNotificationCentercurrentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError *_Nullable error) {
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
// END: Code to addreturnYES;
}- In same file, above
@endadd the following to send the device token to Intercom when permission is granted:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[IntercomModule setDeviceToken:deviceToken];
}
@endAdd URL types
Setup of React Native deep links can be found Here
- Add import to
AppDelegate.m
#import"AppDelegate.h"
#import<React/RCTBridge.h>
#import<React/RCTBundleURLProvider.h>
#import<React/RCTRootView.h>
#import<React/RCTLinkingManager.h><--Add this- Add below code to
AppDelegate.mabove@end
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}
@endSee the example app for an example of how to handle deep linking in your app.
Sets the user hash necessary for validation when Identity Verification is enabled. This should be called before any registration calls.
| Type | Type | Required |
|---|---|---|
| userHash | string | yes |
Promise<boolean>
Registers an unidentified user with Intercom
Promise<boolean>
Registers an identified user with Intercom
One of below fields is required.
| Type | Type | Required |
|---|---|---|
| string | no | |
| userId | string | no |
Promise<boolean>
Updates a user in Intercom.
You can send any data you like to Intercom. Typically our customers see a lot of value in sending data that
Intercom.updateUser({email: 'name@intercom.com',userId: 'userId',name: 'Name',phone: '010-1234-5678',languageOverride: 'languageOverride',signedUpAt: 1621844451,unsubscribedFromEmails: true,companies: [{createdAt: 1621844451,id: 'companyId',monthlySpend: 100,name: 'CompanyName',plan: "plan",customAttributes: {city: "New York"},}],customAttributes: {userCustomAttribute: 123,hasUserCustomAttribute: true}});| Type | Type | Required |
|---|---|---|
| userId | string | no |
| string | no | |
| name | string | no |
| phone | string | no |
| languageOverride | string | no |
| signedUpAt | number (timestamp) | no |
| unsubscribedFromEmails | boolean | no |
| companies | array | no |
| customAttributes | object {key: boolean,string, number} | no |
Promise<boolean>
Logout is used to clear all local caches and user data the Intercom SDK has created. Use this at a time when you wish to log a user out of your app or change a user. Once called, the SDK will no longer communicate with Intercom until a further registration is made.
Promise<boolean>
Logs an event with a given name and some metadata.
| Type | Type | Required |
|---|---|---|
| eventName | string | yes |
| metaData | object {key: boolean,string,number} | no |
Promise<boolean>
This takes a push registration token to send to Intercom to enable this device to receive push.
| Type | Type | Required |
|---|---|---|
| token | string | yes |
Promise<boolean>
Gets the number of unread conversations for a user.
Promise<number>
Handles the opening of an Intercom push message. This will retrieve the URI from the last Intercom push message.
useEffect(()=>{/** * Handle PushNotification Open */constappStateListener=AppState.addEventListener('change',(nextAppState)=>nextAppState==='active'&&Intercom.handlePushMessage());return()=>AppState.removeEventListener('change',()=>{});// <- for RN < 0.65return()=>appStateListener.remove();// <- for RN >= 0.65},[]);Promise<boolean>
Opens the Intercom Messenger automatically to the best place for your users.
Promise<boolean>
Open the conversation screen with the composer pre-populated text.
| Type | Type | Required |
|---|---|---|
| initialMessage | string | no |
Promise<boolean>
Open up your apps help center
Promise<boolean>
Present the help center with specific collections only .
| Type | Type | Required |
|---|---|---|
| collections | string[] | no |
Promise<boolean>
Fetch a list of all Collections.
Promise<HelpCenterCollectionItem[]>
Get a list of sections/articles for a collection.
| Type | Type | Required |
|---|---|---|
| collectionId | string | yes |
Promise<HelpCenterCollectionContent>
Get a list of articles in the Help Center, filtered by a search term
| Type | Type | Required |
|---|---|---|
| searchTerm | string | yes |
Promise<HelpCenterArticleSearchResult[]>
Displays article with given id.
| Type | Type | Required |
|---|---|---|
| articleId | string | yes |
Promise<boolean>
Displays carousel
| Type | Type | Required |
|---|---|---|
| carouselId | string | yes |
Promise<boolean>
Opens an article
| Type | Type | Required |
|---|---|---|
| articleId | string | yes |
Promise<boolean>
Toggles visibility of in-app messages.
| Type | Type | Required |
|---|---|---|
| visibility | string GONE, VISIBLE | yes |
Promise<boolean>
Toggles visibility of the launcher view. Set as Intercom.Visibility.GONE to hide the launcher when you don't want it to be visible.
| Type | Type | Required |
|---|---|---|
| visibility | string GONE, VISIBLE | yes |
Promise<boolean>
Set the bottom padding of in app messages and the launcher.
Setting the bottom padding will increase how far from the bottom of the screen the default launcher and in app messages will appear
| Type | Type | Required |
|---|---|---|
| bottomPadding | number | yes |
Promise<boolean>
Set the level of the native logger
| Type | Type | Required |
|---|---|---|
| logLevel | string(ASSERT, DEBUG, DISABLED, ERROR, INFO, VERBOSE, WARN) | yes |
Promise<boolean>
Sets a listener for listed events:
| Event | Platform |
|---|---|
| IntercomUnreadConversationCountDidChangeNotification | IOS, Android |
| IntercomHelpCenterDidShowNotification | IOS |
| IntercomHelpCenterDidHideNotification | IOS |
| IntercomWindowDidShowNotification | IOS |
| IntercomWindowDidHideNotification | IOS |
useEffect(()=>{constlistener=Intercom.addEventListener('IntercomUnreadConversationCountDidChangeNotification',({count})=>alert(count);return()=>{listener.remove();}},[])| Type | Type | Required |
|---|---|---|
| event | string (IntercomEvents) | yes |
| callback | function ({count?: number, visible?: boolean}) => void | yes |
EmitterSubscription
typeHelpCenterArticle={it: string;title: string;};typeHelpCenterSection={name: string;articles: HelpCenterArticle;};typeHelpCenterCollectionItem={id: string;title: string;summary: string;};typeHelpCenterCollectionContent={id: string;name: string;summary: string;articles: HelpCenterArticle[];sections: HelpCenterSection[];};typeHelpCenterArticleSearchResult={id: string;title: string;matchingSnippet: string;summary: string;};- To enable
jetifier, add those two lines to yourgradle.propertiesfile:android.useAndroidX=true android.enableJetifier=true
- To enable
- Add those lines to
dependenciesin./android/app/build.gradle:implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha03'
- Add those lines to
When tests with Jest fail mentioning "Cannot read property 'UNREAD_CHANGE_NOTIFICATION' of undefined"
- Make a
jest.mockfunction with the library:// jest/setup.ts jest.mock('@intercom/intercom-react-native', () => jest.fn());
- Make a
👤 Intercom (https://www.intercom.com/)
Give a ⭐️ if this project helped you!
This project is MIT licensed.
Created with ❤️ by Intercom
