DEV Community

Cover image for React Native: Two-Way Bridging with Android Native Modules
Amit Kumar
Amit Kumar

Posted on • Edited on

React Native: Two-Way Bridging with Android Native Modules

React Native is a powerful framework that enables developers to build mobile apps using JavaScript and React. But what happens when you need to interact with platform-specific code, like accessing native Android features? Thatโ€™s where Native Modules come into play.

In this blog post, weโ€™ll walk through a simple yet effective example of creating a native module in Android and bridging it with React Native. Weโ€™ll:

  • Call a native method from React Native to get a message
  • Send data from React Native to the Android side

๐Ÿงฉ Step-by-Step Guide

๐Ÿ“ 1. Define Your Interface

Create a Kotlin class called HelloWorldModule.kt inside android/app/src/main/java/com/nativebridging/HelloWorldModule.kt:

package com.nativebridging

import android.util.Log
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Callback
import com.facebook.react.bridge.ReadableMap

class HelloWorldModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "HelloWorld"
    }

    @ReactMethod
    fun sayHello(successCallback: Callback) {
        successCallback.invoke("Hello World from Android!")
    }

    @ReactMethod
    fun receivedData(data: ReadableMap, callback: Callback) {
        Log.d("ReactNative", "Received data: ${data.toString()}")

        val userName = data.getString("userName") ?: "No username"
        val age = data.getString("age") ?: "No age"
        Log.d("ReactNative", "Username: $userName, Age: $age")

        // Send response back to JS
        callback.invoke("Data received successfully")
    }
}
Enter fullscreen mode Exit fullscreen mode

Screenshot for reference

Image description


๐Ÿ” What's Happening Here?

  • sayHello: Sends a simple string response to the React Native side.
  • receivedData: Receives a ReadableMap from React Native and logs the contents, then sends a confirmation back.

๐Ÿ“ฆ Step 2: Register the Native Module with React Native

Create a HelloWorldPackage.kt inside android/app/src/main/java/com/nativebridging/HelloWorldPackage.kt:

package com.nativebridging

import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager

class HelloWorldPackage : ReactPackage {
    override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
        return listOf(HelloWorldModule(reactContext))
    }

    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
        return emptyList()
    }
}

Enter fullscreen mode Exit fullscreen mode

Screenshot for reference

Image description


Then register this package in your MainApplication.kt file:

            PackageList(this).packages.apply {
              // Packages that cannot be autolinked yet can be added manually here, for example:
              // add(MyReactNativePackage())
                add(HelloWorldPackage()) // ๐Ÿ‘ˆ Add this line
            }

Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Step 3: Call Native Methods from React Native

Now let's build the React Native part.

App.js (or App.tsx)

import {StyleSheet, View, NativeModules, Button, Alert} from 'react-native';
import React from 'react';

const App = () => {
  const {HelloWorld} = NativeModules;

  const getMessageFromAndroid = () => {
    HelloWorld.sayHello(msg => {
      Alert.alert('Message from Android', msg);
    });
  };

  const sendMessageToAndroid = () => {
    HelloWorld.receivedData(
      {
        userName: '[email protected]',
        age: '30',
      },
      response => {
        Alert.alert('Android Response', response);
      },
    );
  };

  return (
    <View style={styles.container}>
      <Button
        title="Get Message from Android"
        onPress={getMessageFromAndroid}
      />

      <Button title="Send Data to Android" onPress={sendMessageToAndroid} />
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: 20,
  },
});

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฒ What Youโ€™ll See in Action

  • When you tap "Get Message from Android", an alert will pop up with the message "Hello World from Android!".
  • When you tap "Send Data to Android", the Android logs will print the user data, and an alert will confirm receipt.

๐Ÿ”š Wrapping Up

With just a few lines of code, you've built a bridge between your JavaScript world and the native Android layer! This is extremely useful for integrating SDKs or platform-specific features that arenโ€™t exposed to React Native out of the box.


โœ… Key Takeaways:

  • Use @ReactMethod in your native module to expose Android functions.
  • Always register the native module via a ReactPackage.
  • Use NativeModules in React Native to call native code.

Native modules give React Native superpowers ๐Ÿ’ฅ โ€” start using them to unlock more of what Android has to offer.

Top comments (0)