Reputation: 927
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.
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
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