react-native-eval
v0.1.0
Published
Call any JS functions from your native code
Downloads
29
Maintainers
Readme
react-native-eval
React has a good tutorial how to integrate React View to alrady existsing application, but it doesn't provide a good way if you decided to migrate some of your business logic to JS first while maintaining the same UI.
Installation
- Make sure that npm and cocoapods initialized:
npm init && pod init
npm install --save react-native-eval
- Add following line to Podfile:
pod 'react-native-eval',:path => 'node_modules/react-native-eval'
pod install
Usage
- Get a referenct to
RCTBridge
, by getting it fromRCTRootView.bridge
that you have created (if you have any React Native view) or by creatingRCTBridge
manually:
RCTBridge* bridge = [[RCTBridge alloc] initWithBundleURL:[NSURL URLWithString:@"URL_TO_BUNDLE"]
moduleProvider:nil
launchOptions:nil];
RCTRootView* view = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"app"];
// Call sync function
[RNMEvaluator callSyncFunction:bridge
name:@"Math.pow"
args:@[@2,@2]
cb:^(NSString *error, id returnValue) {
if (error)
NSLog(@"Error occured: %@", error);
else
NSLog(@"Function returned: %@", returnValue);
}];
// You can call async function as well. It has to have callback as a last argument.
// If callback would be called with Error object then it will be converted to
// NSString and passed as a first argument of native callback. Otherwise callback
// value would be passed as a second parameter
[RNMEvaluator callAsyncFunction:bridge
name:@"(function(a,b,cb) { setTimeout(function() { cb(Math.pow(a,b)) },0) })"
args:@[@2,@2]
cb:^(NSString *error, id returnValue) {
if (error)
NSLog(@"Error occured: %@", error);
else
NSLog(@"Function returned: %@", returnValue);
}]
On a JS side be sure to call require('RNMEvaluator')
, otherwise needed JS wouldn't be included to the output