Native languages (like Java/Kotlin for Android and Objective-C/Swift for iOS) and React Native typically communicate with each other through a mechanism called "bridging." Native code can be called from JavaScript (React Native) and the other way around
// NativeModuleClass.java
public class NativeModuleClass extends ReactContextBaseJavaModule {
@ReactMethod
public void showNativeAlert(String message) {
Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
// ...other methods
}
// App.js
import React from 'react';
import { Button, View } from 'react-native';
import { NativeModules } from 'react-native';
const NativeModuleClass = NativeModules.NativeModuleClass;
const App = () => {
return (
<View>
<Button
title="Show Native Alert"
onPress={() => NativeModuleClass.showNativeAlert('Hello from React Native!')}
/>
</View>
);
};
export default App;
// NativeModuleClass.m
@implementation NativeModuleClass
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(showNativeAlert:(NSString *)message) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Native Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}
// ...other methods
@end
// App.js
import React from 'react';
import { Button, View } from 'react-native';
import NativeModuleClass from './NativeModuleClass'; // Path to your Objective-C module
const App = () => {
return (
<View>
<Button
title="Show Native Alert"
onPress={() => NativeModuleClass.showNativeAlert('Hello from React Native!')}
/>
</View>
);
};
export default App;
// NativeModuleClass.java
// ...same as for Native Modules
// Other class/file
EventDispatcher dispatcher = new EventDispatcher(getReactApplicationContext());
...
dispatcher.emit("nativeEvent", "Some data from native code");
// App.js
import React from 'react';
import { View, Text } from 'react-native';
import { NativeEventEmitter, NativeModules } from 'react-native';
const NativeModuleClass = NativeModules.NativeModuleClass;
const eventEmitter = new NativeEventEmitter(NativeModuleClass);
eventEmitter.addListener("nativeEvent", (data) => {
console.log("Received native event:", data);
// Update your UI or perform actions here
});
const App = () => {
return (
<View>
<Text>Waiting for native events...</Text>
</View>
);
};
export default App;