DEV Community

Cover image for How to Create a Simple Android Bridge in React Native
Amit Kumar
Amit Kumar

Posted on • Edited on

How to Create a Simple Android Bridge in React Native

In React Native, sometimes you need to access native functionality that's not available in JavaScript. For such cases, React Native allows you to create a bridge between JavaScript and native code. In this blog, we'll create a simple Android native module in React Native that returns "Hello World" from Android to JavaScript.

What We'll Build

We'll create a native Android module in Java that sends a "Hello World" message back to the React Native JavaScript side. We'll then display this message in the app using a simple component.

Step 1: Create a Native Android Module

To get started, navigate to your Android project inside your React Native app:

cd android/app/src/main/java/com/yourprojectname/

Enter fullscreen mode Exit fullscreen mode

Inside the Java directory, we will create a new directory named nativeModules, where our native module will live.

Image description

1.1 Create the HelloWorldModule.java Class

Inside nativeModules, create a new Java class called HelloWorldModule.java. This class will define our native module.

package com.yourprojectname.nativeModules;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;

public class HelloWorldModule extends ReactContextBaseJavaModule {

    public HelloWorldModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

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

    @ReactMethod
    public void sayHello(Callback successCallback) {
        // Send "Hello World" message back to the JavaScript side
        successCallback.invoke("Hello World from Android!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Here, we define a method getHelloWorldMessage that sends back a "Hello World" string when called from JavaScript. This method is annotated with @ReactMethod, which makes it accessible from React Native.

Image description

1.2 Create the HelloWorldPackage.java Class

Next, create another Java class called HelloWorldPackage.java in the same folder. This class will register our module with React Native.

package com.yourprojectname.nativeModules;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelloWorldPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new HelloWorldModule(reactContext)); // Register the module
        return modules;
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

Enter fullscreen mode Exit fullscreen mode

This HelloWorldPackage class registers our HelloWorldModule so that React Native can access it.

Image description

Step 2: Register the Module in MainApplication.java

To make our native module available in the React Native app, we need to register it in the MainApplication.java file. Open MainApplication.java located at:

android/app/src/main/java/com/yourprojectname/MainApplication.java

Enter fullscreen mode Exit fullscreen mode

In the getPackages() method, add your HelloWorldPackage to the list:

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        packages.add(new HelloWorldPackage());  // Add this line
    );
}

Enter fullscreen mode Exit fullscreen mode

This ensures that the package (and by extension, the module) is included in the React Native app.

Step 3: Access the Native Module in JavaScript

Now that we’ve created our native module, let's access it in our JavaScript code.

Open the App.js file (or any other file where you want to use this native module) and use NativeModules to call the sayHello method.

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

const App = () => {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Access the native HelloWorld module and call getHelloWorldMessage
    NativeModules.HelloWorld.getHelloWorldMessage((msg) => {
      setMessage(msg);
    });
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>{message}</Text>
    </View>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

In this code:

  • We call NativeModules.HelloWorld.getHelloWorldMessage which triggers the method we created in the native module.
  • The message is passed back from Android, and we display it using React's Text component.

To send data to Android side

To send data from React Native to the native side in the HelloWorldModule, your setup works similarly to the previous example. Here's a recap with the updated module name:

Native Side (Kotlin)

The receivedData method in HelloWorldModule:

@ReactMethod(isBlockingSynchronousMethod = true)
fun receivedData(options: ReadableMap) {
    Log.d("data-->>", options.toString())

    val userName = options.getString("userName")
    val userAge = options.getString("userAge")
}

Enter fullscreen mode Exit fullscreen mode
  • The @ReactMethod annotation makes this method accessible from React Native.
  • ReadableMap captures the passed object, and you extract values using getString.

React Native Side

From the React Native side, you send the data using:

NativeModules.HelloWorldModule.receivedData({
    userName: "amit@gmail.com",
    age: "29",
});

Enter fullscreen mode Exit fullscreen mode

NativeModules.HelloWorldModule is called to send the userName and age fields to the native method.

This ensures the data is correctly passed from React Native to your Kotlin module.

Step 5: Conclusion

That's it! You've successfully created a native Android module in React Native and accessed it from the JavaScript side. This is a simple example, but the process is the same for more complex native functionality like interacting with device hardware, sensors, or integrating third-party SDKs.

Native modules are a powerful feature of React Native that allows you to go beyond what JavaScript can do by tapping into the native APIs provided by Android and iOS.

If you need more complex functionality, you can extend this module further by adding more methods or incorporating other native Android APIs.

After reading the post consider the following:

  • Subscribe to receive newsletters with the latest blog posts
  • Download the source code for this post from my github

Top comments (0)