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") } }
Screenshot for reference
๐ 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() } }
Screenshot for reference
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 }
๐ก 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: 'amit@gmail.com', 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, }, });
๐ฒ 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)