Install and set up React Native plugin

This article provides information on how to install and set up Blueshift's React Native plugin to integrate your mobile app with our platform.

Installing Blueshift's React Native plugin for the Blueshift iOS and Android SDK is pretty straightforward. Follow the step-by-step instructions provided.

Install the plugin

Run the npm command to install the Blueshift React Native plugin.

npm install blueshift-react-native

Android and iOS Integration

To integrate the Blueshift SDK for Android and iOS, see the following topics in the documentation:

Use the plugin

Import the Blueshift plugin in your JS/TS to use its functionality.

import Blueshift from 'blueshift-react-native';

Initialize the plugin as soon as the app starts. One could do this method call from componentDidMount callback or from the useEffect depending upon their implementation. (min plugin version - 1.0.2)

Blueshift.init();

After you import the plugin, you can call the Blueshift methods.

// Call Blueshift functions
Blueshift.setUserInfoEmailId("[email protected]");
Blueshift.identifyWithDetails({"user_type":"premium"});

For information about the features and methods supported by the plugin and how to use them, see Blueshift JS methods.

Set user information

Using the plugin, you can set the information for the logged-in user in the Blueshift SDK. The SDK adds this user data to each event and sends it to the Blueshift server. This user data can be saved when the user logs in to the app and must be removed when the user logs out of the app.

In order to associate the events with the correct user, three primary identifiers are used to identify a user uniquely.

  • DeviceID - This is auto-generated by SDK and sent to the Blueshift server as the device_id attribute in every event.
  • EmailId - Email ID must be set whenever it changes as mentioned in the following code snippet and this is sent to the Blueshift server as part of every event.
  • CustomerId - Customer ID must be set whenever it changes as mentioned in the following code snippet and this is sent to the Blueshift server as part of every event.

Ensure that you fire an identify event after making changes to the user data so that the changes are reflected on the Blueshift server.

// Set data on successful login 
Blueshift.setUserInfoEmailId("[email protected]");
Blueshift.setUserInfoCustomerId("cust123456");

// Set other user info. This info is used for creating 
// segments or running personalized campaigns 
Blueshift.setUserInfoFirstName("John");
Blueshift.setUserInfoLastName("Cartor");
Blueshift.setUserInfoExtras({"profession":"software engineer", "isLoggedIn":true});

// Clear the stored data at the time of logout
Blueshift.removeUserInfo();

Identify event

The Identify event is used to update the data for the user profile on the Blueshift server. Whenever you change any user data in the Blueshift SDK, we recommend you fire an identify event to reflect those changes on the Blueshift server. This ensures that we can continue to attribute the events to the correct user and generate recommendations for the user in case the device_id is reset due to the uninstalling of the app by the user.

// Set user data at login
Blueshift.setUserInfoEmailId("[email protected]");
Blueshift.setUserInfoCustomerId("cust123456");
Blueshift.setUserInfoExtras({"profession":"software engineer", "isLoggedIn":true});

// Identify event with custom data
Blueshift.identifyWithDetails({"user_type":"premium"});

Custom Event

Use the following method to track custom events with custom data in your app.

Blueshift.trackCustomEvent("name_of_event",{},false);

Push and in-app notification opt-out

Push notifications opt-out

Use Blueshift app preferences to opt-out of push notifications that we send from the Blueshift platform. You can use it if you don't want push notifications from the Blueshift platform to show up on your device. After modifying the value, fire an identify event to update the data on the Blueshift server.

// set the preference for push notifications
Blueshift.setEnablePush(false);

// fire identify event
Blueshift.identifyWithDetails({});

In-app notifications opt-out

Use Blueshift app preferences to opt-out of In-app notifications that we send from the Blueshift platform. You can use it if you don't want in-app notifications from the Blueshift platform to show up on your device. After modifying the value, fire an identify event to update the data on the Blueshift server.

// set the preference for push notifications
Blueshift.setEnableInApp(false);

// fire identify event
Blueshift.identifyWithDetails({});

Delay Push permission dialog (iOS only)

Blueshift SDK registers for iOS push notifications automatically after the app launch. If you don't want the push notification permission window to be displayed immediately on the app launch, you can customize it to display it later after sign up/sign in. For that, you must set the config.enablePushNotification as false in your Xcode project while initializing the Blueshift Plugin.

// Disable push notifications in the SDK configuration 
// to delay the Push notification permission dialog
[config setEnablePushNotification:NO];

You can invoke the following plugin method from your React Native JS/TS when you want to register for push notifications and display the push notification window.

// Register for remote notifications using SDK. 
// Calling this method will show push permission window to the user.
Blueshift.registerForRemoteNotification();

In-App Notifications

Once you enable the in-app notifications from the SDK as mentioned in the Android and iOS set-up documents, you must register the screens in order to see in-app messages. You can register the screens using one of the following two ways.

  • Register all screens Refer to the Android and iOS integration documents to register all screens to receive in-app notifications. After completing this set up, in-app notifications can be displayed on any screen when it is available to display.

  • Register and unregister each screen of your react native project for in-app messages. If you don’t register a screen for in-app messages, the in-app messages will stop showing up for screens that are not registered. You must add in-app registration and unregistration code on the componentDidMount and componentWillUnmount respectively inside your react native screens. Refer to the following example code snippet.

componentDidMount() { 
    // Register for in-app notification
    Blueshift.registerForInAppMessage("HomeScreen");
  }
  
 componentWillUnmount() {
    // Unregister for in-app notification
    Blueshift.unregisterForInAppMessage();
 }

Mobile Inbox

A mobile inbox contains in-app messages that are delivered directly to the inbox in a non-intrusive manner or displayed within the app while also being delivered to the inbox. Users will continue to see these messages in their inbox, until the messages expire or until they delete them after reading.

Blueshift's SDK automatically synchronizes the mobile inbox across all devices on which a user has installed your app and logged in, ensuring the message status (read/unread) is consistent.

The Blueshift React Native Plugin offers a default user interface for the mobile inbox, which you can customize to match your brand's style and colors.

To save in-app messages to an inbox, your app must utilize Blueshift's React Native Plugin version 1.1.0 or above. Additionally, you need to enable the mobile inbox feature in the Android and iOS configurations.

The Inbox is provided as a component and allows for further customization. You can create an empty screen and add the Blueshift Inbox component to it, and the Plugin will handle the rest.

The below code shows how you can use the default Blueshift Inbox component on a screen

import React, {Component} from 'react';
import BlueshiftInbox from 'blueshift-react-native/components/BlueshiftInbox';

export default function InboxScreen() {
  // default inbox
  return <BlueshiftInbox />;
}

The Blueshift Inbox screen offers the flexibility to customize various fields according to your requirements. The following example demonstrates how you can personalize the Inbox component by passing specific parameters.

import React, {Component} from "react";
import {StyleSheet, Text, View} from "react-native";
import BlueshiftInbox from "blueshift-react-native/components/BlueshiftInbox";

export default function InboxScreen() {
  // Mobile inbox customisation
  return (
    <BlueshiftInbox
      unreadIndicatorColor="#ff0000"
      pullToRefreshColor="#00ff00"
      titleStyle={{color: "green", fontSize: 18, fontWeight: "bold"}}
      detailsStyle={{color: "blue", fontSize: 16, fontWeight: "normal"}}
      timestampStyle={{color: "red", fontSize: 14, fontWeight: "normal"}}
      dateFormatterFn={date => date.toLocaleTimeString()}
      sortMessagesFn={(m1, m2) => (m1.createdAt > m2.createdAt ? 1 : -1)}
      deleteComponent={<Text style={{color: "white"}}>Clear</Text>}
      placeholderComponent={<Text>This is an empty place.</Text>}
      listItemSeparatorComponent={
        <View style={{backgroundColor: "blue", height: 2}} />
      }
      listItemComponent={message => (
        <Text>
          {message.title} {message.details}
        </Text>
      )}
    />
  );
}

You have the ability to customize the following elements:

  1. unreadIndicatorColor: Specify the color for the indicator of unread messages.
  2. pullToRefreshColor - Specify the loading indicator color that will appear during pull to refresh and asynchronous in-app loading (iOS only).
  3. titleTextStyle: Specify the text style for the inbox message title text.
  4. detailsTextStyle: Specify the text style for the inbox message details text.
  5. timestampStyle: Specify the text style for the inbox message date text.
  6. dateFormatterFn: Specify a date formatting function to change the default date format in the list.
  7. sortMessagesFn: Specify message sort function to change to sorting order if required.
  8. deleteComponent - Specify a delete component to change the default delete text.
  9. placeholderComponent: Specify a placeholder component to display when the inbox list is empty.
  10. listItemSeparatorComponent: Specify the component to be displayed for the row separators.
  11. listItemComponent: Customize the look and feel of the inbox list item according to your brand's theme.

These options provide you with the flexibility to tailor the Blueshift Inbox screen to your exact preferences and requirements.

Deep link handling

Deep links for the Inbox-originated in-app notifications are sent to the same event listener as push and in-app. You can see more information here.

Event Listeners and Deep links

Get Push notification payload on React Native

The Blueshift plugin delivers the Push notification payload using the event PushNotificationClickedEvent when the user clicks on the push notification. Add a custom event listener using the Blueshift method in your react project.

// Add custom event listener using Blueshift method
Blueshift.addEventListener('PushNotificationClickedEvent',this.handlePushClick );

handlePushClick(payload) {
  alert("push payload "+JSON.stringify(payload));
}

Remove the custom event listener by calling the Blueshift removeEventListener method.

// Remove custom event listner using Blueshift method
Blueshift.removeEventListener('PushNotificationClickedEvent');

🚧

Please note that the PushNotificationClickedEvent is emitted by the iOS platform when the notification is clicked. The same is unavailable for Android platform at the moment.

Deep links for Push and In-app notifications

The Blueshift plugin takes care of delivering the deep link added inside the Push and in-app notifications to the react-native once the user interacts with the notification.

The Blueshift plugin delivers the deep link to react-native using the url event. You must add an event listener using the default Linking method as follows in your react project to receive the deep link.

componentDidMount() { 
  // Add event listner for `url` event
  global.urlListener = Linking.addEventListener('url', (event) => { 
    var url = event.url;
    if(url) {
        this.handleDeeplinkUrl(url);
      }
  });
}

componentWillUnmount() {
  // You must unregister these callbacks
  global.urlListener.remove();
}

handleDeeplinkUrl(url) {
  // Handle the received deep link to perform action.
}

Deep links for Email links

Email deep links are basically App links for Android and Universal links for iOS. To enable the App links and Universal links you must set them up as mentioned in the Android and iOS integration documentation.

Once set up is completed, you can modify the existing url event listener added for Push and In-app deep links to process the email deep links. It should look like the following example.

componentDidMount() { 
  // Get the email deep link when app launched from killed state
  Linking.getInitialURL().then(url => { 
    if(url) {
      // Check if the email deep link from Blueshift
      if (Blueshift.isBlueshiftUrl(url)) {
      	  // Process the email deep link to get original url
        Blueshift.processBlueshiftUrl(url);
      }
    }
  });

  // Add event listner for `url` event
  global.urlListener = Linking.addEventListener('url', (event) => { 
    var url = event.url;
    if(url) {
      // Check if the email deep link from Blueshift
      if (Blueshift.isBlueshiftUrl(url)) {
        // Process the email deep link to get original url
        Blueshift.processBlueshiftUrl(url);
      } else {
        this.handleDeeplinkUrl(url);
      }
    }
  });
}

componentWillUnmount() {
  // You must unregister these callbacks
  global.urlListener.remove();
}

handleDeeplinkUrl(url) {
  // Handle the received deep link to perform action.
}