How to pass an object back from a React Native Android module to Javascript

React Native's Native Module documentation for Android says that ReadableMap directly maps to a Javascript object. I assume this means that when I pass an object from Javascript to a native module, it is available as a ReadableMap.

How do I do the reverse, which is to create a dictionary (mapping string to string) in a native module and return it to Javascript via a callback?

2 Answers

You can use WritableMap to simply pass map values through callback.

@ReactMethod public void pass(Callback cb) { HashMap<String, String> hm = new HashMap<>(); hm.put("A", "one"); hm.put("B", "Two"); hm.put("C", "Three"); WritableMap map = new WritableNativeMap(); for (Map.Entry<String, String> entry : hm.entrySet()) { map.putString(entry.getKey(), entry.getValue()); } cb.invoke(map); } 

for more complex data, see this blog.

For React Native >=0.62, you can use this:

import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.Arguments; @ReactMethod public void test(Callback callback) { WritableMap map = Arguments.createMap(); map.putString("yourKey", "yourValue"); callback.invoke(map); } 

To call the native function in React Native, do this:

import { NativeModules } from 'react-native'; NativeModules["replaceWithTheModuleName"].test(res => { console.log(res); }) 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like