fish
fish

Reputation: 113

How to call javascript method in react-native on Android platform?

When I click a button in native UI (probably from a fragment container) , I wanna invoke a method from JavaScript, let's call it just like 'jsMethod' or other else. However, I have never handled this situation before.

I am looking up some relative codes from Facebook's document on website and can not find out the key to the problem so far. Anyone give me some suggestions?

Upvotes: 9

Views: 7910

Answers (1)

Petter Hesselberg
Petter Hesselberg

Reputation: 5518

To call a JavaScript method from Java, do something like this:

ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();

CatalystInstance catalystInstance = reactContext.getCatalystInstance();
WritableNativeArray params = new WritableNativeArray();
params.pushString("Message to show using nameOfJsMethod");
catalystInstance.callFunction("JavaScriptVisibleToJava", "nameOfJsMethod", params);

The JavaScript method you want to call must be defined and made visible to Java:

import BatchedBridge from "react-native/Libraries/BatchedBridge/BatchedBridge";

export class ExposedToJava {
  nameOfJsMethod(message) {
    alert(message);
  }
}

const exposedToJava = new ExposedToJava();
BatchedBridge.registerCallableModule("JavaScriptVisibleToJava", exposedToJava);

This sample on Github includes a working demo.

EDIT I'm told this approach is not officially documented. If your scenario allows, consider taking the advice of @ufxmeng (in the comment to the OP) instead.

Upvotes: 17

Related Questions