How to Create Bridge in React Native for iOS and Android?
React Native is developed in such a way that we will create a bridge between the language and therefore the JavaScript code. A “bridge” is nothing but how to line up communication between native platform and React Native.
React Native is developed in such a way that we will create a bridge between the language and therefore the JavaScript code. A “bridge” is nothing but how to line up communication between native platform and React Native.
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
We have also clicked on Create Bridging Header which can create a file LightApp-Bridging-Header.h this may help to
speak between Swift and Objective C code. Remember that during a project we've just one Bridge Header file. So if we
add new files, we will reuse this file.
Update following code in LightApp-Bridging-Header.hfile:
#import “React/RCTBridgeModule.h”
RCTBridgeModule will arrange an interface to join a bridge module.
Next update Bulb.swift with the subsequent code:
Import Foundation
@objc(Bulb)
Class Bulb : NSObject {
@objc
Static var isOn = false
@objc
Func turnOn(){
Bulb.isOn = true
Print (“Bulb is now ON”)
}
}
We have created a Bulb class which is inherited from NSObject. The base class of most Objective-C class ranking is
NSObject, from which subclasses acquire a basic interface to the runtime system and therefore the capability to behave
as Objective-C objects. we will see that we've used @objc before a function and sophistication , this may make that class,
function or object available to Objective C
React Native won't expose any function of Bulb to React JavaScript unless explicitly done. to try to do so we've used
RCT_EXPORT_METHOD() macro. So we've exposed the Bulb class and turnOn function to our Javascript code. Since Swift
object is converted to Javascript object, there's a kind of conversation. RCT_EXPORT_METHOD supports all standard
JSON object types:
NSString to string
NSInteger, float, double, CGFloat, NSNumber to number
BOOL to boolean
NSArray to array
NSDictionary to object with string keys and values of any type from this list
RCTResponseSenderBlock to function
Now let’s modernize JavaScript code and approach this Bulb class from our React component. to try to to so open App.js
and update with the subsequent code: