Pass Data from Native Module to JS module in React Native (Android)

December 16, 2022

1. Create New Project and Setup native module functionality using official documentation of React-Native native Module of android.

2. Import NativeModules and DeviceEventEmitter into the React native.

import {
  View,
  Text,
  Button,
  NativeModules,
  DeviceEventEmitter,
} from 'react-native';
import React, {useEffect} from 'react';

3. Create an Activity into the Native Android and call it from created Native Module like :

public class NativeCallBack extends ReactContextBaseJavaModule {
    Promise mPromise;
    NativeCallBack(ReactApplicationContext context) {
        super(context);
    }

    @NonNull
    @Override
    public String getName() {
        return "NativeCallBack";
    }

    @ReactMethod
    public void callNativeModule(Promise promise) {
        mPromise = promise;
        final Activity activity = getCurrentActivity();
        Intent intent = new Intent(activity, CallBackActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getReactApplicationContext().startActivity(intent);
    }
}

4. Create a function “sendEvent” ( name can be anything) and Call this function at button click. we can see into the image “How function is called into the native module”.

“reactContext” should be initialized before using it.

public class CallBackActivity extends ReactActivity {
    ReactInstanceManager mReactInstanceManager;
    ReactApplicationContext context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_back);
        mReactInstanceManager = CallBackActivity.this.getReactNativeHost().getReactInstanceManager();
        context = (ReactApplicationContext) mReactInstanceManager.getCurrentReactContext();
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) Button nativeButton = (Button) findViewById(R.id.nativeButton);

//        this is data to be passed from native module to JSmodule
        WritableMap payuData = Arguments.createMap();
        payuData.putString("PayuResponses", "Native data    ");
        payuData.putString("MerchantData", "send");

        nativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                We are returning back data from native module to JSmodule on button press on native side
                sendEvent(context,"NATIVEEVENT",payuData);
                CallBackActivity.this.finish();
            }
        });
    }
    private void sendEvent(ReactContext reactContext,
                           String eventName,
                           @Nullable WritableMap params) {
        Log.d("sss", "enter");
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                //supply the result in params
                .emit(eventName, params);
    }
}

5. Now coming back to JS module. use “useEffect” to call “DeviceEventEmitter” to get data from Native Module.

React.useEffect(() => {
    //  we will use deviceEventEmitter for getting data from native module
    DeviceEventEmitter.addListener('NATIVEEVENT', payuResponseGet);
  }, []);

6. payuResponseGet is the function where we get the data.

  const payuResponseGet = data => {
    console.log(JSON.stringify(data));
    setText(data.PayuResponses)
  };

This is all about DeviceEventEmitter by which we can get data from native module to JS module.


Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow