Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple react-native native module with a callback

How to get this work, in the simplest way, I have trouble getting the callback send to react-native, probably I'm missing something.

@ReactMethod
public void testCallback(Callback cb) {

String sampleText = "Java is fun";
int textLength = sampleText.length();
    try{
        cb.invoke(textLength);
    }catch (Exception e){
        cb.invoke("err");
    }
}

On react-native side

var getNativeCallback = require('react-native-native-callback');


getNativeCallback.testCallback(function (result){
    console.log(result)
})
like image 902
syarul Avatar asked Oct 25 '15 02:10

syarul


People also ask

How do you write native modules in React Native?

To add native modules to react-native, let's create a new Kotlin class named 'NativeModuleManagerPackage'. We will implement ReactPackage in this file which will expose our native code to react-native. For registering the NativeModuleManagerPackage , we have to add code in MainApplication. kt as well.

How do you call a native method in React Native?

In order to access your native module from JavaScript you need to first import NativeModules from React Native: import { NativeModules } from 'react-native'; You can then access the CalendarModule native module off of NativeModules .

What is callback in React Native?

This callback function is run at a later time, usually through some interaction with the child component. The purpose of this callback function is to change a piece of the state that is a part of the parent component. This closes the data loop.


1 Answers

I have to face the same problem, and finally I have to take a different approach, as apparently, there is no Callback type accepted for @ReactProp.

Instead I used the 'Events' way, in order to have response communication from Android native to React Native.

In the Android side I set up a SendEvent function conveniently fired as it needs:

private void sendEventToReactFromAndroid(ReactContext reactContext,String eventName, @Nullable WritableMap params) {
    reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}

@Override
public void customAndroidListenerFunction() {
    sendEvent(mcontext, "EventName", null);

}

Then in the React side, you will expect this event, and parameters if you may like:

var {DeviceEventEmitter} = require('react-native');
...
componentWillMount: function() {
    DeviceEventEmitter.addListener('EventName', function(e: Event) {
        console.log("Received event loud and clear in the React Native side!");
    });
},
...

Hope that helps.

like image 137
Juanan Jimenez Avatar answered Sep 17 '22 09:09

Juanan Jimenez