import React, { useState } from 'react';
import { View, Text, Button, StyleSheet, NativeModules } from 'react-native';
const { DeviceInfoModule } = NativeModules;
export default function NativeModuleDemo() {
const [deviceInfo, setDeviceInfo] = useState(null);
const [loading, setLoading] = useState(false);
const getDeviceInfo = async () => {
setLoading(true);
try {
const info = await DeviceInfoModule.getDeviceName();
setDeviceInfo(info);
} catch (e) {
setDeviceInfo('Error fetching device info');
}
setLoading(false);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Native Module Demo</Text>
<Text style={styles.label}>Device Info:</Text>
<Text style={styles.info}>{loading ? 'Loading...' : deviceInfo || ''}</Text>
<Button title="Get Device Info" onPress={getDeviceInfo} />
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 20, justifyContent: 'center' },
title: { fontSize: 24, marginBottom: 20, textAlign: 'center' },
label: { fontSize: 18, marginBottom: 10 },
info: { fontSize: 16, marginBottom: 20 }
});This example shows how React Native uses native modules to access device features that JavaScript alone cannot reach. We import NativeModules from React Native and get a reference to a native module called DeviceInfoModule. This module is assumed to be implemented natively (in Java or Swift) and exposes a method getDeviceName that returns the device's name.
When the user taps the button, we call this native method asynchronously. We show a loading message while waiting. Once the info is received, we display it on screen. This demonstrates how native modules extend React Native's capabilities by bridging to platform-specific code.