React Native’s RCT_EXTERN_METHOD
Most of the Objective-C Macros from React Native that you have to use when bridging native code are self-explanatory and easy to use. But there is something weird about RCT_EXTERN_METHOD
at first sight.
It took me quite some time to understand how it works. There’s no detailed documentation about this, so I will try my best to explain it.
Note:
RCT_EXPORT_METHOD
works exactly the same
As the name implies, these Macros enable us to expose a native method to React Native’s bridge. It has the following syntax:
RCT_EXTERN_METHOD(
methodName: (paramType1)internalParamName1
externalParamName2: (paramType2)internalParamName2
externalParamName3: (paramType3)internalParamName3
...
)
Probably the best way to understand it is from some examples:
Example with no arguments
This is the easiest example. You just need to specify the method name:
// Obj-C
RCT_EXTERN_METHOD(getCount)// Swift
func getCount() {...}
Example with 1 argument
In this scenario, the external name of the argument maps to the method name and the internal name of the argument maps to the corresponding Swift argument. Since the argument doesn’t have an external name, we use “_” instead:
// Obj-C
RCT_EXTERN_METHOD(getCount:(NSString)name)// Swift
func getCount(_ name: NSString) {...}
Example with 2 arguments
For the 1st argument, the above rules apply. Starting with the second argument, the external and internal names map as we would expect:
// Obj-C
RCT_EXTERN_METHOD(getCount:(NSString)name withAge:(NSNumber)age)// Swift
func getCount(_ name: NSString, withAge age: NSNumber) {...}
If you want to learn more about using Swift code in React Native, you should check out Swift in React Native - The Ultimate Guide: