React-Native allows user to create bridges to access native code from JavaScript. Once you have created your own bridges you might want to share them with the community. This article will explain in a few simple steps how to do so.
1. Create a new project with react-native-create-library
Open your terminal and run
react-native-create-library --package-identifier org.domain --platforms android,ios native-bridge
This will create a new project name react-native-native-bridge with all the required files in there.
2. Implement your bridge
Open the Xcode project located in the react-native-native-bridge/ios folder and edit the RNNativeBridge.m file to add your bridge functions accordingly. Here is a simple example that will return “Hello from Xcode!” when called in React-Native
RCT_EXPORT_METHOD(greetings: (RCTResponseSenderBlock)callback){ callback(@[[NSNull null], @"Hello from Xcode!" ]); }
If you are not familiar with native modules, go check the great documentation here.
3. Create a new npm package and publish it
Now that our hyper sophisticated bridge library is ready😉, we will propose it as an npm package on npmjs. You first need to create a new account on npmjs if you don’t have one yet. You can run
npm whoami
to check if you are logged in or not. If not, just run
npm adduser
and follow the instructions. Update the package.json file accordingly and run
npm publish
The new package will now be available to the community via the npm command and you can also see it at https://npmjs.com/package/react-native-native-bridge. You can refer to the documentation if you need any help.
4. Create a new React-Native demo app and use the package
Let’s create a new React Native project to test the npm package. Open your terminal and run
react-native init nativeBridgeTest
Install the react-native-native-bridge package and link it
npm install react-native-native-bridge react-native link react-native-native-bridge
Open the App.js file of your React Native project and edit as follow
import RNNative Bridge from react-native-native-bridge ... // create a new function in the App class greetings = () => { RNNativeBridge.greetings( (err, res) => { console.log(res); }); } ... // Add a button in the render() function that will call the native function when clicked <Button title="Greetings" onPress={this.greetings} />
This should print “Hello from Xcode!” in the logs.
Sources:
Creating a React Native Bridge Library
We can work together
Share this post on social media:
How do I implement Swift framework with this react native library and call from NativeModules. I have implemented React Native library, however unable to connect Swift framework.
I don’t think there is an option to directly use your Swift framework in React Native without having some objective-c code in between.