Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a similar way to export constants (using constantsToExport) from native module on Android as on iOS?

Tags:

react-native

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!

like image 393
cookiecookie Avatar asked Dec 26 '16 05:12

cookiecookie


2 Answers

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;
  }
like image 192
Mahmoud Avatar answered Nov 15 '22 11:11

Mahmoud


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.

like image 35
cookiecookie Avatar answered Nov 15 '22 13:11

cookiecookie