Introduction:
One of the most powerful features of React Native is its ability to seamlessly bridge between JavaScript and native platform code, giving us the power to access platform-specific features. While React Native provides many built-in APIs, there are times when you need to write your own native modules for platform-specific functionality or third-party SDKs that aren't available by default.
In this article, we’ll start with the basics of integrating native modules into React Native. We’ll show how to create a simple native module that accesses the device’s battery status. In the next part of this tutorial series, we’ll explore more complex real-world scenarios, like integrating PacificSDK for interacting with Electronic Logging Devices (ELDs).
1. What Are Native Modules in React Native?
React Native allows us to access native code from JavaScript. This is achieved through native modules—a bridge between JavaScript and platform-specific code (Java for Android, Objective-C/Swift for iOS).
Native modules are useful for:
Accessing device hardware or sensors (e.g., battery status, camera).
Integrating third-party SDKs or libraries.
Enhancing app performance by handling heavy operations on the native side.
While React Native provides a wide range of APIs, certain features require writing platform-specific code. That’s where native modules come in.
2. Setting Up Your Environment
Before jumping into the code, let’s ensure your development environment is ready to handle both Android and iOS platforms:
Install React Native CLI:
npm install -g react-native-cli
npx react-native init MyNativeModuleApp
npx react-native run-android
npx react-native run-ios
Install Android Studio & Xcode:
You’ll need Android Studio for Android development and Xcode for iOS development. Follow the official documentation for installing these tools.
3. Creating a Basic Native Module: Battery Status
Let’s begin by creating a simple native module to fetch the battery status of the device. We’ll implement it for both Android and iOS.
Step 1: Create the Native Module for Android (Java)
- Navigate to your React Native project and create a new file called
BatteryStatusModule.java
inside theandroid/app/src/main/java/com/{yourproject}/
directory. package com.yourproject;
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 android.os.BatteryManager;
import android.content.Context;
public class BatteryStatusModule extends ReactContextBaseJavaModule {
public BatteryStatusModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "BatteryStatusModule";
}
@ReactMethod
public void getBatteryStatus(Callback callback) {
BatteryManager batteryManager = (BatteryManager) getReactApplicationContext().getSystemService(Context.BATTERY_SERVICE);
int batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
callback.invoke(null, batteryLevel);
}
}
This code accesses the device’s battery manager to fetch the current battery level and passes it to the JavaScript side using a callback.
Step 2: Create the Native Module for iOS (Objective-C)
- In the
ios/YourProjectName
directory, create a new fileBatteryStatusModule.m
#import "BatteryStatusModule.h"
#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
#import <UIKit/UIKit.h>
@implementation BatteryStatusModule
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(getBatteryStatus:(RCTResponseSenderBlock)callback)
{
UIDevice *device = [UIDevice currentDevice];
[device setBatteryMonitoringEnabled:YES];
float batteryLevel = device.batteryLevel * 100; // Battery level as a percentage
callback(@[@(batteryLevel)]);
}
@end
Here, we use the UIDevice class to access the battery level and pass the result to JavaScript via a callback.
Step 3: Linking the Native Modules
- Android
In android/app/src/main/java/com/{yourproject}/MainApplication.java
, add the BatteryStatusModule
to the list of packages:
import com.yourproject.BatteryStatusModule; // Add this import
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new BatteryStatusModule() // Add the module here
);
}
-
iOS:
In the
ios/YourProjectName/YourProjectName.m
file, import and register theBatteryStatusModule
:
#import "BatteryStatusModule.h"
No additional registration is necessary in iOS since React Native automatically picks up native modules.
4. Calling Native Code from JavaScript
Now that the native module is set up and linked, let’s use it in JavaScript. To call the native module, we’ll use React Native’s NativeModules API.
import { NativeModules } from 'react-native';
const { BatteryStatusModule } = NativeModules;
BatteryStatusModule.getBatteryStatus((error, batteryLevel) => {
if (error) {
console.error(error);
} else {
console.log(`Battery level is: ${batteryLevel}%`);
}
});
This will print the device’s battery level in the JavaScript console.
5. Conclusion: What’s Next?
In this article, we’ve learned how to create and link a simple native module in React Native, starting with fetching the device’s battery status. This is the foundation you’ll need when integrating more complex native functionality, such as third-party SDKs.
In the next part of this tutorial series, we’ll take this knowledge further and integrate PacificSDK, a real-world SDK that allows us to communicate with Electronic Logging Devices (ELDs) for fleet management and compliance.
Stay tuned for the next article, where we’ll dive into working with ELD devices and handling real-world scenarios!
Top comments (0)