I am new to react and working on react bridging modules. I just want to know that how the RCTConvert is useful and how can use that. I am following this site link
Please, anyone helps me to know about this stuff.
I am new to react and working on react bridging modules. I just want to know that how the RCTConvert is useful and how can use that. I am following this site link
Please, anyone helps me to know about this stuff.
The RCTConvert
helper functions all accept a JSON value as input and map it to a native Objective-C type or class. It's useful to convert basic supported input parameter types such as NSString
, NSNumber
, NSArray
, NSDictionary
to other ones: NSURL
, UIColor
, CGRect
etc. which are not supported by the React bridge. For instance:
Java Script:
Module.setPosition({x : 10, y: 20});
ObjC:
RCT_EXPORT_METHOD(setPosition:(id)position) {
CGPoint point = [RCTConvert CGPoint:position];
NSLog(@"x: %f, y: %f", point.x, point.y);
}
// Prints: x: 10.000000, y: 20.000000
Also it's possible to extend RCTConvert
with RCT_CUSTOM_CONVERTER
macro for your custom types:
Java Script:
Module.addUser({name : 'John', email: 'joghn@domain.com'});
ObjC:
typedef struct {
NSString* name;
NSString* email;
} User;
User createUser(NSString* name, NSString* email) {
User user;
user.name = name;
user.email = email;
return user;
};
@implementation RCTConvert (User)
RCT_CUSTOM_CONVERTER(User, User, createUser(json[@"name"], json[@"email"]) )
@end
...
RCT_EXPORT_METHOD(addUser:(id)user) {
User new_user = [RCTConvert User:user];
NSLog(@"name: %@, email: %@", new_user.name, new_user.email);
}
// Prints: name: John, email: joghn@domain.com
For simple types such as NSString
it does type checking and rices the conversion error if you try to cast to the other type so that is very important in debugging. This is code for that from the sources:
RCTConvert.h
+ (NSString *)NSString:(id)json;
RCTConvert.m
/**
* This macro is used for creating converter functions for directly
* representable json values that require no conversion.
*/
#if RCT_DEBUG
#define RCT_JSON_CONVERTER(type) \
+(type *)type : (id)json \
{ \
if ([json isKindOfClass:[type class]]) { \
return json; \
} else if (json) { \
RCTLogConvertError(json, @ #type); \
} \
return nil; \
}
#else
#define RCT_JSON_CONVERTER(type) \
+(type *)type : (id)json \
{ \
return json; \
}
#endif
RCT_JSON_CONVERTER(NSArray)
RCT_JSON_CONVERTER(NSDictionary)
RCT_JSON_CONVERTER(NSString)
RCT_JSON_CONVERTER(NSNumber)
For more samples how to use RCTConvert
you can look at the sources: https://github.com/facebook/react-native/blob/master/React/Base/RCTConvert.m