Jerry
Jerry

Reputation: 927

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 sendAppEventWithName 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 sendDeviceEventWithName should work but actually it's also deprecated.

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

Upvotes: 4

Views: 4551

Answers (1)

Jerry
Jerry

Reputation: 927

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.

MyModule.h

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

@interface MyModule : RCTEventEmitter <RCTBridgeModule>

@end

MyModule.m

@implementation MyModule

RCT_EXPORT_MODULE();

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

@end

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))

Upvotes: 7

Related Questions