Developing for React Native

improve this page | report issue
Develop your React Native applications by following the tutorials bellow: set-up your development environment, experience the product and add value by integrating with Mobile Foundation 8.0 offerings.

If you are a developer who has chosen React Native as the framework to develop your mobile or web app, the following sections help you get started with IBM Mobile Foundation SDK in your React Native app.

You can use your preferred code editor such as Atom.io, Visual Studio Code, Eclipse, IntelliJ or any other editor for writing your applications.

Step 1: Installing the React Native CLI

To get started with React Native development the first step required is to install the React Native CLI.

To install React Native CLI:

Download and install NodeJS.

From a Command-line window, run the following command:

    npm install -g react-native-cli
   

Follow the instructions provided in the Getting Started page in React Native docs, to set up your machine for React Native development.

This includes the setup required for Android & iOS.

Step 2: Setting up the MobileFirst development environment

After you have installed the React Native CLI, set up the MobileFirst development environment. For detailed information, refer to the tutorial Setting up the MobileFirst development environment to set up your MobileFirst development environment.


Go to Quick Start tab, to learn how to quickly get started with development using React Native SDK.

Follow the steps below to quickly get started with development using React Native on MobileFirst Platform Foundation.

The purpose of this quick start tutorial is to explain a simple end-to-end flow.

A sample application is provided in Github, the sample is downloaded and registered with MobileFirst Server. The provided adapter (or a new adapter) is deployed to the MobileFirst Operations Console. The application logic is changed to make a resource request.

Expected result: To successfully ping the MobileFirst Server and to successfully retrieve data using an adapter.

Step 1: Starting the MobileFirst Server

Make sure you have created a Mobile Foundation instance, or if you are using the MobileFirst Developer Kit, navigate to the server's folder and run the command: ./run.sh in Mac and Linux or run.cmd in Windows.

Step 2: Adding the React Native SDK

Step 2.1: Downloading the React Native sample application from Github.

Step 2.2: Adding the React Native SDK to the downloaded React Native sample application

The MobileFirst SDK for React Native is available as a React Native module from NPM.

  1. Navigate to the root of your downloaded React Native project and add the MobileFirst core React Native plug-in, change directory to the root of the React Native project: cd MFPStarterReactNative
  2. Add the MobileFirst Plugins by using the NPM CLI command: npm install react-native-plugin-name
    For example:
            npm install react-native-ibm-mobilefirst --save
          
    The above command adds MobileFirst Core SDK Plugin to the React Native project.
  3. Link all native dependencies to your app
            react-native link
          
    Note: This step is not required for react-native version 0.60 and above.

Step 2.3: Additional platform specific steps

Android


Add the following lines to AndroidManifest.xml ({project-folder}/android/app/src/main/) :
      <![CDATA[
      <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"  package="com.myapp">
        ...
        <application tools:replace="android:allowBackup"
        ...
      </application>
    ]]>
    

iOS


Install Mobilefirst specific cocopods dependencies to the project. cd ios && pod install This step is applicable only for the iOS platform.

Step 3: Registering the application

  1. Open a command-line window and navigate to the root of the particular platform (iOS or Android) of the project.
            cd ios
          
    or
            cd android
          
  2. Run the following command to register the application:
            mfpdev app register
          

    If a remote server is used, use the command mfpdev server add to add it. The mfpdev app register CLI command first connects to the MobileFirst Server to register the application. Each platform is registered as an application in MobileFirst Server.

    • iOS

      If your platform is iOS then you are asked to provide the application’s BundleID. Important: The BundleID is case sensitive.

      The mfpdev app register CLI command first connects to the MobileFirst Server to register the application, then updates the mfpclient.plist configuration file at the root of the Xcode project which contains metadata that identifies the MobileFirst Server.

      Note : In XCode, in the project navigator, drag and drop mfpclient.plist from ios folder. This step is applicable only for iOS platform.

    • Android

      If your platform is Android then you are asked to provide the application’s package name. Important: The package name is case sensitive.

      The mfpdev app register CLI command first connects to the MobileFirst Server to register the application, followed by generating the mfpclient.properties file in the [project root]/app/src/main/assets/ folder of the Android Studio project and to add to it the metadata that identifies the MobileFirst Server.

Step 4: Editing the application logic

  1. Open the React native project in your code editor of choice.
  2. Import the WLAuthorizationManager class into your App.js
  3.          import {WLAuthorizationManager, WLResourceRequest} from 'react-native-ibm-mobilefirst';
             
  4. Select the App.js file, which is located at project's root folder and paste the following code snippet, replacing the existing WLAuthorizationManager.obtainAccessToken() function:
    See the React Native Client-side API references here.
             WLAuthorizationManager.obtainAccessToken("").then(
              (token) => {
                console.log('-->  pingMFP(): Success ', token);
                var resourceRequest = new WLResourceRequest("/adapters/javaAdapter/resource/greet/",
                  WLResourceRequest.GET
                );
                resourceRequest.setQueryParameters({ name: "world" });
                resourceRequest.send().then(
                  (response) => {
                    // Will display "Hello world" in an alert dialog.
                    alert("Success: " + response.responseText);
                  },
                  (error) => {
                    console.error(error);
                    alert("Failure: Resource Request");
                  }
                );
              }, (error) => {
                console.error(error);
                alert("Failed to connect to MobileFirst Server");
            });
           

Step 5: Deploying an adapter

Download this prepared .adapter artifact and deploy it from the MobileFirst Operations Console using the Actions → Deploy adapter action.

Step 5.1: Select the Actions → Download sample option. Download the Hello World Java adapter sample

Alternatively, click the New button next to Adapters.

If Maven and MobileFirst CLI are not installed, follow the on-screen Set up your development environment instructions.

Step 5.2: From a Command-line window, navigate to the adapter's Maven project root folder and run the command:

    mfpdev adapter build
  

Step 5.3: When the build finishes, deploy it from the MobileFirst Operations Console using the Actions → Deploy adapter action. The adapter can be found in the [adapter]/target folder.

Step 6: Testing the application

Use the following command to run the application:

     react-native run-ios|run-android
    

If a device is connected, the application is installed and launched in the device. Otherwise the simulator or emulator will be used.

For detailed instructions on quick start steps, see here.

Results

  • Clicking the Ping MobileFirst Server button will display Connected to MobileFirst Server.
  • If the application is able to connect to the MobileFirst Server, a resource request call using the deployed Java adapter takes place. The adapter response is then displayed in an alert.

React Native SDK for IBM MobileFirst JSONStore

The IBM Mobile Foundation JSONStore is an optional client-side API providing a lightweight, document-oriented storage system. JSONStore enables persistent storage of JSON documents. Documents in an application are available in JSONStore even when the device is offline. This persistent, always-available storage can be useful to give users access to documents when,for example, there is no network connection available in the device.

Installation

IBM MobileFirst JSONStore SDK for React Native apps depends on the IBM MobileFirst Foundation SDK. Add the IBM MobileFirst Foundation SDK to your app.

Navigate to the folder of your React Native app and run the following command to install the JSONStore SDK for React Native apps.

      npm install react-native-ibm-mobilefirst-jsonstore --save
      
Supported platforms are Android and iOS.

Getting started

Prerequisites

Create a React Native Project

  1. The first step is to create a React Native project. Let's call the app as the JSONStoreApp. Use the React Native CLI to create a new project.
          react-native init JSONStoreApp
          cd JSONStoreApp
          
  2. Install the MobileFirst Core SDK and complete the Getting Started Instructions.
  3. Add the IBM MobileFirst JSONStore SDK to your app.
          npm install react-native-ibm-mobilefirst-jsonstore —-save
          
  4. Link your project so that all native dependencies are added to your React Native project.
          react-native link
          
    Note: This command is not required from react-native 0.60 and above.

Configure your Android App

  • Add the following lines to the android section of /android/app/build.gradle:
        packagingOptions{
        	exclude 'META-INF/ASL2.0'
        }
        

Creating a JSONStore Collection

The first step in using the JSONStore API is to create a JSONStore Collection.

  1. Import the JSONStore classes into your application. Open App.js and add the following line among the other import statements
        import {WLJSONStore, JSONStoreCollection} from 'react-native-ibm-mobilefirst-jsonstore';
        
  2. Create and open a collection. You can open multiple collections at the same time. Pass a JSONStoreInitOptions parameter for advanced options such as protecting your collection with a password, setting up sync policies etc.
        var dogs = new JSONStoreCollection('dogs');
        WLJSONStore.openCollections(['dogs']);  // Provide the name of the collection as a string.
        

Adding data to a collection

Add JSON data to your collection.

    	var hachi = { "name" : "Hachiko" , "breed" : "Akita" , "country" : "Japan"};
        dogs.addData(hachi).then( ()=> {
          // Data was added to the collection successfully.
        }).catch ( (err) => {
          // Error adding data. See the err object for more information on the error
        })
    

Querying data from a collection

Use any of the JSONStoreCollection.find* APIs to query a collection. Use JSONStoreQueryPart and JSONStoreQuery APIs for advanced filtering and querying of JSON data.

    	dogs.findAllDocuments().then( (result) => {
           // result will have all the documents in the collection
           // E.g. [ {"json": {"name":"Hachiko","breed":"Akita","country":"Japan"},"_id":2}]
         }).catch((error) => {
            console.error ("Error finding docs " +  JSON.stringify(error));
         });
    

Closing, clearing and destroying your collection

Closing your collection will close your JSONStore collection for further access until it is opened again using the openCollections API.

    WLJSONStore.closeAll()
    

Clearing a collection will remove all documents from a collection but does not destroy it.

    	dogs.clearCollection().then (()=>{
    		// All documents cleared successfully
         }).catch( (err) => {
           // An error occurred while clearing the collection.
         })
    

Destroying a collection will permanently delete all data, all accessors and security artifacts. A collection once destroyed cannot be restored. All collections of the app will be destroyed.

    	WLJSONStore.destroy()
    

React Native SDK for IBM MobileFirst Live Update

The Live Update feature in Mobile Foundation provides a simple way to define and serve different configurations for users of an application. It includes a component in the MobileFirst Operations Console for defining the structure of the configuration as well as the values of the configuration.
LiveUpdate React Native SDK lets you query runtime configuration properties and features which you set in the **Live Update Settings** screen in the MobileFirst Operations Console. With Live Update integrated in your application you can implement feature toggling, A/B testing, feature segmentation and more.

Installation

IBM MobileFirst Live Update SDK for React Native apps depends on the IBM MobileFirst Foundation SDK. Add the IBM MobileFirst Foundation SDK to your app.

Navigate to the folder of your React Native app and run the following command to install the Live Update SDK for React Native apps.

      npm install react-native-ibm-mobilefirst-liveupdate --save
      

Getting started

Prerequisites

Create a React Native project

  1. The first step is to create a React Native project. Let's call the app as the MFLiveUpdateApp. Use the React Native CLI to create a new project.
            react-native init MFLiveUpdateApp
            
  2. Add the React Native plugin to your app.
            cd MFLiveUpdateApp
            npm install react-native-ibm-mobilefirst-liveupdate —-save
            
    Note: Live Update package supports React Native v0.62.x and above.
  3. Install Mobilefirst specific cocopods dependencies to the project.
            cd ios && pod install
            

Configure your application

Android

Make the following changes to AndroidManifest.xml (/android/app/src/main/).
  • Add xmlns:tools="http://schemas.android.com/tools" to the manifest tag. For example,
          <manifest
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.mobilefirstapp">
          
  • Add tools:replace="android:allowBackup" to the application tag. For example,
          <application
          android:name=".MainApplication"
          android:label="@string/app_name"
          android:icon="@mipmap/ic_launcher"
          android:allowBackup="false"
          android:theme="@style/AppTheme"
          tools:replace="android:allowBackup">
          

iOS

  • Install Mobilefirst specific cocopods dependencies to the project.
          cd ios && pod install
          
    This step is applicable only for iOS platform.

Test the applciation

Android

  • To run the application,
          react-native run-android
          

iOS

  • To run the application,
          react-native run-ios
          

Supported platforms

  • Android
  • iOS

Configuration in MobileFirst Operation Console

  1. Add a scope mapping for liveupdate.mobileclient in MobileFirst Operations Console → [your application] → Security tab → Scope-Elements Mapping. Map it to an empty string if you want to use the default protection or to a security check if you're using one.
    Learn more about scope mapping.
  2. You can add schemas and features from the MobileFirst Operations Console → [your application] → Live Update Settings.

Once you've set up schemas and features you can start use the client side API.

Sample usage of the API

      var useClientCache = false; //True (default)

      var featureId = 'featureId';
      var propertyId = 'propertyId' ;

      MFLiveUpdate.obtainConfiguration(useClientCache)
      .then(result => {

      console.log('Is feature enabled for' + featureId + ':' + result.isFeatureEnabled('featureId'));
      console.log ('Property value for the ' + propertyId + 'is :' +result.getProperty('propertyId'));


      })
      .catch(err => console.log('There was an error:' + err))
      

Further reading

For details on JSONStore in React Native applications, see here.
For more information about Live Update, see here.

Reference

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on July 02, 2020