The document demonstrates the steps to create react native module bridge in Android and iOS.
Below are the steps for creating a native bridge in Android.

ANDROID

Open the Android Studio with the corresponding project from your react native project.

Step 1 :

Create the Java class that extends ReactPackage. (eg: AndroidModulePackage.java). Implement the interface methods (createViewManagers & createNativeModules…refer step3).

Example:

    public class AndroidModulePackage implements ReactPackage {

    }

Step 2 :

Create the Java Class that extends ReactContextBaseJavaModule. (eg : WifiManager.java)

This is the class you are going to refer in React Native.

Example:

    public class WifiManager extends ReactContextBaseJavaModule{

    }

Step 3 :

Modify the “ReactPackage”(AndroidModulePackage) class to add the “ReactContextBaseJavaModule”(WifiManager) class.

Make sure you add all the modules you use in react native to the Application class “createNativeModules module collection”.

Check the below line in the example

    modules.add(new WifiManager(reactContext));

Example:

    public class AndroidModulePackage implements ReactPackage {

        @Override
        public List<ViewManager> createViewManagers
                     (ReactApplicationContext reactContext) {
            return Collections.emptyList();
        }

        @Override
        public List<NativeModule> createNativeModules(
                ReactApplicationContext reactContext) {
            List<NativeModule> modules = new ArrayList<>();
            modules.add(new WifiManager(reactContext));
            return modules;
        }

    }

Step 4:

Modify the Application class to add the ReactPackage (AndroidModulePackage).

Check the below line in the example.

    new AndroidModulePackage()

Example:

     public class MainApplication extends Application 
                                  implements ReactApplication {

      private final ReactNativeHost mReactNativeHost 
                                  = new ReactNativeHost(this) {

        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          return Arrays.<ReactPackage>asList(
              new MainReactPackage(),
                  new AndroidModulePackage()
          );
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

      };

      @Override
      public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
      }

      @Override
      public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
      }

    }

Step 5:

The function which you wish to call from React should have a “@ReactMethod” annotation as shown below.

Example:

 

     public class WifiManager extends ReactContextBaseJavaModule 
                                     implements Handler.Callback {

        public WifiManager(ReactApplicationContext reactContext) {
            super(reactContext);
        }

        @Override
        public String getName() {
            return TAG;
        }

        @Override
        public Map<String, Object> getConstants() {
            final Map<String, Object> constants = new HashMap<>();
            return constants;
        }

        @ReactMethod
        public void connectToWifi(String wifiSSID) {
            Log.i(TAG, "Call from React Native : connectToWifi");
        }

      }

 

Sending Callback to React

Add the below function in the Java class to send callback to react.


     private void sendEvent(ReactContext reactContext,
                               String eventName,
                               @Nullable WritableMap params) {
            reactContext
                    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit(eventName, params);
     }

Example Usage:

      WritableMap params = Arguments.createMap();
      params.putInt("Key", "value");
      sendEvent(reactContext, "EventKey", params);

=====================================================================================================

Below are the steps for creating a native bridge in iOS.

IOS

Step 1:

Open the Xcode with the corresponding project from your react native project.

Step 2:

Create a objective C or Swift Class which extends the NSObject and implements the “RCTBridgeModule” interface.

Below example is written in objective C.

Example:

    #import <React/RCTBridgeModule.h>
    @interface DemoModule : NSObject <RCTBridgeModule>

Step 3:

Create methods that you want to access from React Native. It should have a “RCT_EXPORT_METHOD” prefix and may have “RCTResponseSenderBlock” if you want callback to React.

In the below example “addEvent” is the function which accepts two parameters from React and logs them in native.

If you want to send the control back to react native use the “callback” object. callback accepts an array of objects.

Example:

 

    @implementation DemoModule
    RCT_EXPORT_MODULE();
    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location )
    {
      NSLog(@"%@ %@", name, location);
    }     

    RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
    {
      NSArray *events =  [NSArray arrayWithObjects:@"Data1", @"Data2", nil];
      callback(@[[NSNull null], events]);
    }

    RCT_EXPORT_METHOD(getCallBack:(RCTResponseSenderBlock)callback)
    {
      NSString *message = @"Message from ios native!!!";
      callback(@[message]);
    }

    @end

REACT NATIVE

To access the native classes from Android or iOS, export the classes by using the “NativeModules” library from React Native.

Create a new .js file in react native and the code to export the functions will look like this.

    import { NativeModules } from 'react-native';
    module.exports = NativeModules.WifiManager;   // Android  Module
    module.exports = NativeModules.DemoModule;    // iOS Module

Import this file in the js file you want

    import MyNativeModules from './MyNativeModules';

Calling native functions from React

    MyNativeModules.isConnected(TARGET_SSID);    // android function
    MyNativeModules.addEvent('Hello', 'World');  // ios function

Getting Callback in React

    import { DeviceEventEmitter } from 'react-native'
    ....
    DeviceEventEmitter.addListener(WIFI_STATUS_EVENT, wifiEventCallback.bind(this));
    .....
    function wifiEventCallback(e: Event) {
       console.log("Callback Event Fired : " + JSON.stringify(e.EventKey));
    }

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.