I have been working on a React Native app with native modules. It would be nice to be able to export enums defined on the native side to JS side. On iOS, you can define a constantsToExport method in your Native Module like documented here:
- (NSDictionary *)constantsToExport
{
return @{ @"firstDayOfTheWeek": @"Monday" };
}
However, there doesn't seem to be such a nice way on Android. Am I missing anything or it's simply not provided? Thanks!
According to docs : http://facebook.github.io/react-native/releases/0.41/docs/native-modules-android.html#native-modules
you don't need to put your constants in BaseJavaModule.java
every class that extends ReactContextBaseJavaModule
have an optional method getConstants()
An optional method called getConstants returns the constant values exposed to JavaScript. Its implementation is not required but is very useful to key pre-defined values that need to be communicated from JavaScript to Java in sync.
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
return constants;
}
Answering my own question to help people who may encounter this problem later. In BaseJavaModule.java
file, there is following method:
/**
* @return a map of constants this module exports to JS. Supports JSON types.
*/
public @Nullable Map<String, Object> getConstants() {
return null;
}
This lets you export constants to JavaScript. Should be in the documentation though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With