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