Jerry Jerry - 1 year ago 268
Javascript Question

What is the method can I use to send an event from native module to JS in React Native

According to React Native documentation, you can use

to send an event from native code to JS. But in my XCode, code suggestions tell me that this method is deprecated.

enter image description here

This issue indicates that
should work but actually it's also deprecated.

What is the actual way to send an event to JS?

Answer Source

UPDATE: Please take a look at this issue in which many people gave a lot of useful solutions.

I figured it out by reading its source code. Using the RCTEventEmitter class.


#import "RCTEventEmitter.h"
#import "RCTBridgeModule.h"

@interface MyModule : RCTEventEmitter <RCTBridgeModule>



@implementation MyModule


- (void)tellJS {
  [self sendEventWithName:@"sayHello" body:@"Hello"];


So you can send an event called sayHello with data Hello to JavaScript by calling the tellJS method.

In JavaScript side, you have to use the NativeModules module to get this native module and wrap it in NativeEventEmitter class so that you can receive events.

import { NativeModules, NativeEventEmitter } from 'react-native'

const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule)
myModuleEvt.addListener('sayHello', (data) => console.log(data))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download