import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';
import { NativeModules } from 'react-native';
const { BatteryModule } = NativeModules;
export default function NativeModulesDemo() {
const [batteryLevel, setBatteryLevel] = useState(null);
const [loading, setLoading] = useState(false);
const fetchBatteryLevel = async () => {
setLoading(true);
try {
const level = await BatteryModule.getBatteryLevel();
setBatteryLevel(level);
} catch (error) {
setBatteryLevel(null);
} finally {
setLoading(false);
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Battery Level Demo</Text>
<Text style={styles.batteryText}>Battery Level: {batteryLevel !== null ? `${batteryLevel} %` : '--'}</Text>
{loading && <ActivityIndicator size="small" color="#0000ff" />}
<Button title="Refresh Battery Level" onPress={fetchBatteryLevel} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16
},
title: {
fontSize: 24,
marginBottom: 20
},
batteryText: {
fontSize: 18,
marginBottom: 10
}
});This example shows how to use a native module in React Native. The BatteryModule is assumed to be a native module that provides a method getBatteryLevel() returning a Promise with the battery percentage.
We use React state to store the battery level and a loading flag. When the user taps the button, fetchBatteryLevel calls the native module method asynchronously. While waiting, a spinner shows. When the value arrives, we update the UI with the battery level.
This pattern helps React Native apps access device features not available in JavaScript alone by bridging to native code.