react-native-eval

Call any JS functions from your native code

Usage no npm install needed!

<script type="module">
  import reactNativeEval from 'https://cdn.skypack.dev/react-native-eval';
</script>

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 from RCTRootView.bridge that you have created (if you have any React Native view) or by creating RCTBridge 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