Introduction to communicate between RN and Native

Dave Chao
2 min readJun 28, 2021

--

Sometimes we want to reuse some existing native libraries without having to reimplement it in JavaScript, or write some high performance, we need to communicate with native in RN.

Get Started

Create a Native Module

  • Defined module name.
  • Export a native method to JavaScript via @ReactMethod.
  • Sending events to JavaScript via RCTDeviceEventEmitter.

The native module can then be accessed in JS like this:

const { WizardModule } = ReactNative.NativeModules;

JavaScript modules can then register to receive events by addListener on the NativeEventEmitter class.

import { NativeEventEmitter, NativeModules } from 'react-native';
...
componentDidMount() {
...
const eventEmitter = new NativeEventEmitter(NativeModules.WizardModule);
this.eventListener = eventEmitter.addListener('EventName', (event) => {
console.log(event)
});
...
}
componentWillUnmount() {
this.eventListener.remove();
}

All native module methods meant to be invoked from JavaScript must be annotated with @ReactMethod.

const { WizardModule } = NativeModules;
WizardModule.receiveEvent('receiveData');

Register the Module

In order to do so, you need to add your native module to a ReactPackage and register the ReactPackage with React Native. During initialization, React Native will loop over all packages, and for each ReactPackage, register each native module within.

Start React Native

Build RN SDK

  • Android
react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/wizard_mobile.bundle --assets-dest android/app/src/main/res
  • iOS
react-native bundle --platform ios --dev false --entry-file index.ios.js --bundle-output ./bundles/wizard_mobile.bundle --assets-dest ./bundles

Thanks for reading this and I hope this helped you develop the hybrid app.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Dave Chao
Dave Chao

No responses yet

Write a response