SECRET OF CSS

Native Modules: Export Objective C Modules to React Native | by Wynne Tran | Jun, 2022


Connect Objective-C to React Native

1*0YtpRDW32fcHOgMlF2vHTg

To continue sharing my knowledge about the Native Module with beginners who are working in mobile development, this article shows a simple example of how you can write an application using objective C and export it to React Native. We start with a new React Native app:

npx react-native init NativeModules
NativeModules/ios/NativeModule.xcworkspace
0*kZSH7I9obEfsBZ d

Now, we need to declare our @interface class as NSObject, which will be exported to React Native side:

// ObjC_to_RN.h#import <React/RCTBridgeModule.h>@interface SampleClass : NSObject <RCTBridgeModule>@end
  • We import the @interface class from ObjC_to_RN.h
  • We create an @implement class which includes modules and methods we want to export to React Native
  • Write a simple function
  • Wrap function above and export it to react-native
//ObjC_to_RN.m
#import <Foundation/Foundation.h>
#import "ObjC_to_RN.h"
@implementation SampleClassRCT_EXPORT_MODULE();- (NSString *)hello{
NSLog( @"Hello world !");
return @"Hello world !";
}
RCT_EXPORT_METHOD(sayHello: (RCTResponseSenderBlock)callback{
callback(@[[NSNull null], self.hello]);
});
@end

Go back to our react native folder, and open the App.js:

import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';
const App = () => {
const onPress = () => {
const {SampleClass} = NativeModules;
SampleClass.sayHello((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button
title="Objective C to React Native"
color="#841584"
onPress={onPress}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
1*7uQx N0WcvGDtBg3waFJvA

And we are done.

I hope my article will help people easy to understand how to connect objective C and React Native via Native Module.

1*2M5XnZ50OO3oVdgL06wnhw

Thank you for reading this article, do not forget to give me a clap if you think it is helpful.





News Credit

%d bloggers like this: