Ways to Use Native Modules with Expo
Ways to Use Native Modules with Expo
Expo is a tool that makes application development with React Native easier. However, sometimes you may need to use native modules for custom functionalities. In this article, we will learn how to use native modules with Expo using the bare workflow. This is very important for gaining access to more specific functionalities and platform-specific APIs.
What is Bare Workflow?
Bare workflow allows you to set up your Expo application from scratch. This method gives you more control over your application. When you want to use native modules, you generally need to switch to the bare workflow. At this point, you will need to manually manage your iOS and Android projects.
Switching to Bare Workflow
To switch your Expo application to bare workflow, you should run the following command:
npx expo prebuild
After doing this, you can open the project using Xcode or Android Studio and start adding native modules.
Native Module Example
Native Module for iOS
To create a native module, you can add the code below in the iOS folder. This example is a module that retrieves the device's battery level.
#import <React/RCTBridgeModule.h>
@interface BatteryModule : NSObject <RCTBridgeModule>
@end
@implementation BatteryModule
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(getBatteryLevel:(RCTResponseSenderBlock)callback) {
UIDevice *device = [UIDevice currentDevice];
[device setBatteryMonitoringEnabled:YES];
float batteryLevel = device.batteryLevel;
callback(@[@(batteryLevel)]);
}
@end
Native Module for Android
To create the native module on Android, add the following code in the MainActivity.java file:
public class BatteryModule extends ReactContextBaseJavaModule {
public BatteryModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "BatteryModule";
}
@ReactMethod
public void getBatteryLevel(Promise promise) {
BatteryManager batteryManager = (BatteryManager) getReactApplicationContext().getSystemService(Context.BATTERY_SERVICE);
int batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
promise.resolve(batteryLevel);
}
}
As seen in the examples above, adding custom functionalities for iOS and Android is quite simple. You can invoke your module from your React Native component.
Conclusion
Using native modules with Expo is a great way to add more functionality to your application. By switching to the bare workflow and creating the right native modules, you can add the custom functions you need to your project. The examples we created in this article show how you can get extended functionality using the bare workflow. We wish you success in your app development journey!

Yorum Gönder