A collection of examples for using React Native in an existing iOS application
One of the first things that you should do, if you want decent performance out of your hybrid app, is to pre-load your RCTBridge
and keep a reference of it somewhere (possibly your AppDelegate
):
AppDelegate.h
@property (nonatomic, strong) RCTBridge *bridge;
AppDelegate.m
@synthesize bridge;
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...configure the jsCodeLocation here...
bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation
moduleProvider:nil
launchOptions:launchOptions];
...setup your rootViewController here...
return YES;
}
This will allow the JavaScript to pre-load and allow you to use this bridge later on in other parts of the app:
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:delegate.bridge moduleName:@"MyModule" initialProperties:nil];
In your index.ios.js
file, you can "register" different modules that you want to use as seperate entry points in your app:
var React = require('react-native');
var {
AppRegistry,
} = React;
var MainEntry = require('./Main');
var SecondEntry = require('./Second');
var ThirdEntry = require('./Third');
AppRegistry.registerComponent('MainEntry', () => MainEntry);
AppRegistry.registerComponent('SecondEntry', () => SecondEntry);
AppRegistry.registerComponent('ThirdEntry', () => ThirdEntry);
You can then pass these in as the moduleName
when creating a RCTRootView
:
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:delegate.bridge moduleName:@"SecondEntry"];
React View inside a Native View
UIView
that already exists in UIViewController
.Passing Data into a React View
initialProperties
on RCTRootView
to pass data to your React Native component.Native Modal With RN Navigation
Using a Coordinator native module, we are able to delegate
method calls to the native Obj-C container.
delegate
to the native module instance on the bridge after the RCTBridge
and RCTRootView
are created.For example:
[(MyNativeModule *)[myAppdelegate.bridge.modules[@"MyNativeModule"] setDelegate:self]];
moduleProvider
block to pass in instances of the modules when the bridge loads? Since, we are trying to load the bridge at startup, for performance gains, we don't yet have the instance of all of our view controllers.Coordinator
), but you would need to create your bridges when your container view controller loads, this could cause performance issues if you want your React Native components to display immediately.For example (when loading your container view controller):
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation
moduleProvider:^ NSArray *{
return @[self];
}
launchOptions:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName: @"MyModule"];