reactjs – How do I Expose a React Method on an Android Activity with a ReactRootView so it can be Called From React Native Javascript?-ThrowExceptions

Exception or error:

I have an existing application on both the iOS and Android platforms. Before I start migrating code completely over to React Native, I am dipping my toe in the water by simply displaying a react view in response to a button press from a native view in the app(s).

Now, I am trying to wire up a native function which I can call from react-native javascript code.

I have already done this successfully using iOS. But I’m not sure how to extend the code from the docs in the page I linked previously to make it work in Android.

I didn’t find the React Native docs to be clear enough on how to make this happen on Android.

I have an android app with an activity which I created according to the instructions found in the react-native docs at .

How do I expose the function? and how do I invoke it from Javascript.

How to solve:

So, I figured out how to do this with the help of this SO question and this page.

My mistake was I was trying to put the method I wanted to expose in the java code for the android activity. That was not the correct approach.

Instead, here’s what I had to do:

  1. After following the instructions to integrate react-native into an existing Android app, create a native module (a class that extends ReactContextBaseJavaModule).

    For the sake of this example, lets call the module JNativeCalls

  2. Create a native module package (a class that implements ReactPackage). Let’s call it JNativeCallsPackage

  3. In the java activity, add the JNativeCallsPackage ReactPackage to the code that sets up the ReactInstanceManager using:

    .addPackage(new JNativeCallsPackage())

    This line should be placed on a line right after the line that says .addPackage(new MainReactPackage()) if you have followed the same instructions I did

  4. Then, import the package into the javascript file:

    import {NativeModules} from 'react-native';
  5. Finally, from within your javascript, call the method with:

    NativeModules.YourCustomModuleName.helloWorld("A string message parameter");

Leave a Reply

Your email address will not be published. Required fields are marked *