cookiecookie
cookiecookie

Reputation: 93

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

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!

Upvotes: 5

Views: 3499

Answers (2)

Mahmoud
Mahmoud

Reputation: 1181

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;
  }

Upvotes: 5

cookiecookie
cookiecookie

Reputation: 93

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.

Upvotes: 1

Related Questions