React Native – How to create a native module?

iOS

Open iOS project in XCode

  • Create MyNativeModule.h
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyNativeModule : NSObject <RCTBridgeModule>
@end
NS_ASSUME_NONNULL_END
#import <Foundation/Foundation.h> #import <React/RCTBridgeModule.h> NS_ASSUME_NONNULL_BEGIN @interface MyNativeModule : NSObject <RCTBridgeModule> @end NS_ASSUME_NONNULL_END
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyNativeModule : NSObject <RCTBridgeModule>
@end

NS_ASSUME_NONNULL_END
  • Create MyNativeModule.m
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#import "MyNativeModule.h"
#import <React/RCTLog.h>
@implementation MyNativeModule
// Bridge module name
RCT_EXPORT_MODULE(NativeModuleName);
// Bride method
RCT_REMAP_METHOD(
buildAPIURL, // native API name
param1:(NSString *)baseURL // example
param2:(NSString *)privateKey // example
buildAPIURLWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
...
if (...) {
resolve(result);
} else {
NSError *error = [NSError errorWithDomain:@"React Bridge" code:200 userInfo:@{@"Error reason": @"Invalid Input"}];
reject(@"no_events", @"There were no events", error);
}
}
@end
#import "MyNativeModule.h" #import <React/RCTLog.h> @implementation MyNativeModule // Bridge module name RCT_EXPORT_MODULE(NativeModuleName); // Bride method RCT_REMAP_METHOD( buildAPIURL, // native API name param1:(NSString *)baseURL // example param2:(NSString *)privateKey // example buildAPIURLWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { ... if (...) { resolve(result); } else { NSError *error = [NSError errorWithDomain:@"React Bridge" code:200 userInfo:@{@"Error reason": @"Invalid Input"}]; reject(@"no_events", @"There were no events", error); } } @end
#import "MyNativeModule.h"
#import <React/RCTLog.h>

@implementation MyNativeModule

// Bridge module name
RCT_EXPORT_MODULE(NativeModuleName);

// Bride method
RCT_REMAP_METHOD(
  buildAPIURL, // native API name
  param1:(NSString *)baseURL // example
  param2:(NSString *)privateKey // example
  buildAPIURLWithResolver:(RCTPromiseResolveBlock)resolve
  rejecter:(RCTPromiseRejectBlock)reject) {
    
    ...

    if (...) {
      resolve(result);
    } else {
      NSError *error = [NSError errorWithDomain:@"React Bridge" code:200 userInfo:@{@"Error reason": @"Invalid Input"}];
      reject(@"no_events", @"There were no events", error);
    }
}

@end

Android

Open Android project in Android Studio

  • Create MyNativeModule.java having native Android module
    Java
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.xxxxxx.yyy;
import android.widget.Toast;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
...
public class MyNativeModule extends ReactContextBaseJavaModule {
public MyNativeModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
// Bridge module name
return "NativeModuleName";
}
// Create a native API
@ReactMethod
public void buildAPIURL(final String param1, final String param2, final Promise promise) throws Exception
{
...
promise.resolve(result);
}
// Create another native API
@ReactMethod
public void ToastText(String text) {
Toast.makeText(getReactApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
package com.xxxxxx.yyy; import android.widget.Toast; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableNativeArray; ... public class MyNativeModule extends ReactContextBaseJavaModule { public MyNativeModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { // Bridge module name return "NativeModuleName"; } // Create a native API @ReactMethod public void buildAPIURL(final String param1, final String param2, final Promise promise) throws Exception { ... promise.resolve(result); } // Create another native API @ReactMethod public void ToastText(String text) { Toast.makeText(getReactApplicationContext(), text, Toast.LENGTH_LONG).show(); } }
package com.xxxxxx.yyy;

import android.widget.Toast;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;

...

public class MyNativeModule extends ReactContextBaseJavaModule {

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

    @Override
    public String getName() {
        // Bridge module name
        return "NativeModuleName";
    }

    // Create a native API
    @ReactMethod
    public void buildAPIURL(final String param1, final String param2, final Promise promise) throws Exception
    {
        ...

        promise.resolve(result);
    }

    // Create another native API
    @ReactMethod
    public void ToastText(String text) {
        Toast.makeText(getReactApplicationContext(), text, Toast.LENGTH_LONG).show();
    }
}

Kotlin

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MyNativeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "NativeModuleName";
}
@ReactMethod
@Throws(Exception::class)
fun buildAPIURL(param1: String?, param2: String?, promise: Promise) {
...
promise.resolve(result)
}
@ReactMethod
fun ToastText(text: String?) {
Toast.makeText(reactApplicationContext, text, Toast.LENGTH_LONG).show()
}
}
class MyNativeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "NativeModuleName"; } @ReactMethod @Throws(Exception::class) fun buildAPIURL(param1: String?, param2: String?, promise: Promise) { ... promise.resolve(result) } @ReactMethod fun ToastText(text: String?) { Toast.makeText(reactApplicationContext, text, Toast.LENGTH_LONG).show() } }
class MyNativeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
  override fun getName(): String {
    return "NativeModuleName";
  }

  @ReactMethod
  @Throws(Exception::class)
  fun buildAPIURL(param1: String?, param2: String?, promise: Promise) {
    ...
    promise.resolve(result)
  }

  @ReactMethod
  fun ToastText(text: String?) {
    Toast.makeText(reactApplicationContext, text, Toast.LENGTH_LONG).show()
  }
}
  • Create MyNativeModuleReactPkg.java to register native Android module with React Native
    Java
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.xxxxxx.yyy;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyNativeModuleReactPkg 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 MyNativeModule(
reactContext
));
return modules;
}
}
package com.xxxxxx.yyy; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MyNativeModuleReactPkg 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 MyNativeModule( reactContext )); return modules; } }
package com.xxxxxx.yyy;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyNativeModuleReactPkg 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 MyNativeModule(
            reactContext
        ));

        return modules;
    }
}

Kotlin

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MyNativeModuleReactPkg : ReactPackage {
override fun createViewManagers(
reactContext: ReactApplicationContext
): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf()
override fun createNativeModules(reactContext: ReactApplicationContext): MutableList<NativeModule> {
val modules: MutableList<NativeModule> = ArrayList()
modules.add(
MyNativeModule(
reactContext
)
)
return modules
}
}
class MyNativeModuleReactPkg : ReactPackage { override fun createViewManagers( reactContext: ReactApplicationContext ): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf() override fun createNativeModules(reactContext: ReactApplicationContext): MutableList<NativeModule> { val modules: MutableList<NativeModule> = ArrayList() modules.add( MyNativeModule( reactContext ) ) return modules } }
class MyNativeModuleReactPkg : ReactPackage {

  override fun createViewManagers(
    reactContext: ReactApplicationContext
  ): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf()

  override fun createNativeModules(reactContext: ReactApplicationContext): MutableList<NativeModule> {
    val modules: MutableList<NativeModule> = ArrayList()
    modules.add(
      MyNativeModule(
        reactContext
      )
    )
    return modules
  }
}
  • Edit MainApplication.java
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
...
import com.xxxxxxxxx.yyy.MyNativeModuleReactPkg;
...
@override
protected List<ReactPackage> getPackages() {
...
packages.add(new MyNativeModuleReactPkg());
return packages;
}
... import com.xxxxxxxxx.yyy.MyNativeModuleReactPkg; ... @override protected List<ReactPackage> getPackages() { ... packages.add(new MyNativeModuleReactPkg()); return packages; }
...

import com.xxxxxxxxx.yyy.MyNativeModuleReactPkg;

...

@override
protected List<ReactPackage> getPackages() {

    ...

    packages.add(new MyNativeModuleReactPkg());

    return packages;
}

React Native

Open React Native in Visual Studio Code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { NativeModules } from 'react-native';
const nativeModule = NativeModules.NativeModuleName;
export const getApiUrl = () => {
const promise = new Promise((resolve, reject) => {
const success = (response) => {
resolve(response[0]);
};
const fail = (error) => {
reject(error);
};
// Call an API from native module
nativeModule.buildAPIURL(param1, param2)
.then(success)
.catch(fail);
});
return promise;
};
import { NativeModules } from 'react-native'; const nativeModule = NativeModules.NativeModuleName; export const getApiUrl = () => { const promise = new Promise((resolve, reject) => { const success = (response) => { resolve(response[0]); }; const fail = (error) => { reject(error); }; // Call an API from native module nativeModule.buildAPIURL(param1, param2) .then(success) .catch(fail); }); return promise; };
import { NativeModules } from 'react-native';

const nativeModule = NativeModules.NativeModuleName;

export const getApiUrl = () => {
  const promise = new Promise((resolve, reject) => {
    const success = (response) => {
      resolve(response[0]);
    };

    const fail = (error) => {
      reject(error);
    };

    // Call an API from native module
    nativeModule.buildAPIURL(param1, param2)
      .then(success)
      .catch(fail);
  });

  return promise;
};

Be the first to comment

Leave a Reply

Your email address will not be published.


*