Summary: Will create new issue to add more information to the `Components` section of the Tutorial since that was gutted by this change. Fixes #8156 Closes https://github.com/facebook/react-native/pull/8256 Differential Revision: D3459601 Pulled By: JoelMarcey fbshipit-source-id: 4038afc463bffcf8efda36d29bc7c443bbc8f4bd
29 KiB
id, title, layout, category, permalink, next
| id | title | layout | category | permalink | next |
|---|---|---|---|---|---|
| basics-integration-with-existing-apps | Integration With Existing Apps | docs | Basics | docs/basics-integration-with-existing-apps.html | sample-application-movies |
This section will be updated shortly showing an integration into a more real world application such as the 2048 app that was used for Objective-C and Swift.
Key Concepts
React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.
The keys to integrating React Native components into your iOS application are to:
- Understand what React Native components you want to integrate.
- Create a
Podfilewithsubspecs for all the React Native components you will need for your integration. - Create your actual React Native components in JavaScript.
- Add a new event handler that creates a
RCTRootViewthat points to your React Native component and itsAppRegistryname that you defined inindex.ios.js. - Start the React Native server and run your native application.
- Optionally add more React Native components.
- Debug.
- Prepare for deployment (e.g., via the
react-native-xcode.shscript). - Deploy and Profit!
The keys to integrating React Native components into your iOS application are to:
- Understand what React Native components you want to integrate.
- Install
react-nativein your Android application root directory to createnode_modules/directory. - Create your actual React Native components in JavaScript.
- Add
com.facebook.react:react-native:+and amavenpointing to thereact-nativebinaries innode_nodules/to yourbuild.gradlefile. - Create a custom React Native specific
Activitythat creates aReactRootView. - Start the React Native server and run your native application.
- Optionally add more React Native components.
- Debug.
- Prepare for deployment.
- Deploy and Profit!
Prerequisites
The Android Getting Started guide will install the appropriate prerequisites (e.g., npm) for React Native on the Android target platform and your chosen development environment.
General
First, follow the Getting Started guide for your development environment and the iOS target platform to install the prerequisites for React Native.
CocoaPods
CocoaPods is a package management tool for iOS and Mac development. We use it to add the actual React Native framework code locally into your current project.
$ sudo gem install cocoapods
It is technically possible not to use CocoaPods, but this requires manual library and linker additions that overly complicates this process.
Our Sample App
Assume the app for integration is a [2048](https://en.wikipedia.org/wiki/2048_(video_game) game. Here is what the main menu of the native application looks like without React Native.
Assume the app for integration is a [2048](https://en.wikipedia.org/wiki/2048_(video_game) game. Here is what the main menu of the native application looks like without React Native.
Package Dependencies
React Native integration requires both the React and React Native node modules. The React Native Framework will provide the code to allow your application integration to happen.
package.json
We will add the package dependencies to a package.json file. Create this file in the root of your project if it does not exist.
Normally with React Native projects, you will put files like
package.json,index.ios.js, etc. in the root directory of your project and then have your iOS specific native code in a subdirectory likeios/where your Xcode project is located (e.g.,.xcodeproj).
Below is an example of what your package.json file should minimally contain.
Version numbers will vary according to your needs. Normally the latest versions for both React and React Native will be sufficient.
{
"name": "NumberTileGame",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "15.0.2",
"react-native": "0.26.1"
}
}
{
"name": "swift-2048",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "15.0.2",
"react-native": "0.26.1"
}
}
Packages Installation
Install the React and React Native modules via the Node package manager. The Node modules will be installed into a node_modules/ directory in the root of your project.
# From the directory containing package.json project, install the modules
# The modules will be installed in node_modules/
$ npm install
React Native Framework
The React Native Framework was installed as Node module in your project above. We will now install a CocoaPods Podfile with the components you want to use from the framework itself.
Subspecs
Before you integrate React Native into your application, you will want to decide what parts of the React Native Framework you would like to integrate. That is where subspecs come in. When you create your Podfile, you are going to specify React Native library dependencies that you will want installed so that your application can use those libraries. Each library will become a subspec in the Podfile.
The list of supported subspecs are in node_modules/react-native/React.podspec. They are generally named by functionality. For example, you will generally always want the Core subspec. That will get you the AppRegistry, StyleSheet, View and other core React Native libraries. If you want to add the React Native Text library (e.g., for <Text> elements), then you will need the RCTText subspec. If you want the Image library (e.g., for <Image> elements), then you will need the RCTImage subspec.
Podfile
After you have used Node to install the React and React Native frameworks into the node_modules directory, and you have decided on what React Native elements you want to integrate, you are ready to create your Podfile so you can install those components for use in your application.
The easiest way to create a Podfile is by using the CocoaPods init command in the native iOS code directory of your project:
## In the directory where your native iOS code is located (e.g., where your `.xcodeproj` file is located)
$ pod init
The Podfile will be created and saved in the iOS directory (e.g., ios/) of your current project and will contain a boilerplate setup that you will tweak for your integration purposes. In the end, Podfile should look something similar to this:
# The target name is most likely the name of your project.
target 'NumberTileGame' do
# Your 'node_modules' directory is probably in the root of your project,
# but if not, adjust the `:path` accordingly
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'RCTText',
'RCTWebSocket', # needed for debugging
# Add any other subspecs you want to use in your project
]
end
source 'https://github.com/CocoaPods/Specs.git'
# Required for Swift apps
platform :ios, '8.0'
use_frameworks!
# The target name is most likely the name of your project.
target 'swift-2048' do
# Your 'node_modules' directory is probably in the root of your project,
# but if not, adjust the `:path` accordingly
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'RCTText',
'RCTWebSocket', # needed for debugging
# Add any other subspecs you want to use in your project
]
end
Pod Installation
After you have created your Podfile, you are ready to install the React Native pod.
$ pod install
Your should see output such as:
Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Downloading dependencies
Installing React (0.26.0)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed.
If you get a warning such as "The
swift-2048 [Debug]target overrides theFRAMEWORK_SEARCH_PATHSbuild setting defined inPods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig. This can lead to problems with the CocoaPods installation", then make sure theFramework Search PathsinBuild Settingsfor bothDebugandReleaseonly contain$(inherited).
Code Integration
Now that we have a package foundation, we will actually modify the native application to integrate React Native into the application. For our 2048 app, we will add a "High Score" screen in React Native.
The React Native component
The first bit of code we will write is the actual React Native code for the new "High Score" screen that will be integrated into our application.
Create a index.ios.js file
First, create an empty index.ios.js file. For ease, I am doing this in the root of the project.
index.ios.jsis the starting point for React Native applications on iOS. And it is always required. It can be a small file thatrequires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything inindex.ios.js
# In root of your project
$ touch index.ios.js
Add Your React Native Code
In your index.ios.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class RNHighScores extends React.Component {
render() {
var contents = this.props["scores"].map(
score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text>
);
return (
<View style={styles.container}>
<Text style={styles.highScoresTitle}>
2048 High Scores!
</Text>
<Text style={styles.scores}>
{contents}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
highScoresTitle: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
scores: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
// Module name
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);
RNHighScoresis the name of your module that will be used when you add a view to React Native from within your iOS application.
The Magic: RCTRootView
Now that your React Native component is created via index.ios.js, you need to add that component to a new or existing ViewController. The easiest path is to take is to optionally create an event path to your component and then add that component to an existing ViewController.
We will tie our React Native component with a new native view in the ViewController that will actually host it called RCTRootView .
Create an Event Path
You can add a new link on the main game menu to go to the "High Score" React Native page.
Event Handler
We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play.
When you build a React Native application, you use the React Native packager to create an index.ios.bundle that will be served by the React Native server. Inside index.ios.bundle will be our RNHighScore module. So, we need to point our RCTRootView to the location of the index.ios.bundle resource (via NSURL) and tie it to the module.
We will, for debugging purposes, log that the event handler was invoked. Then, we will create a string with the location of our React Native code that exists inside the index.ios.bundle. Finally, we will create the main RCTRootView. Notice how we provide RNHighScores as the moduleName that we created above when writing the code for our React Native component.
First import the RCTRootView library.
#import "RCTRootView.h"
The
initialPropertiesare here for illustration purposes so we have some data for our high score screen. In our React Native component, we will usethis.propsto get access to that data.
- (IBAction)highScoreButtonPressed:(id)sender {
NSLog(@"High Score Button Pressed");
NSURL *jsCodeLocation = [NSURL
URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL : jsCodeLocation
moduleName : @"RNHighScores"
initialProperties :
@{
@"scores" : @[
@{
@"name" : @"Alex",
@"value": @"42"
},
@{
@"name" : @"Joel",
@"value": @"10"
}
]
}
launchOptions : nil];
UIViewController *vc = [[UIViewController alloc] init];
vc.view = rootView;
[self presentViewController:vc animated:YES completion:nil];
}
Note that
RCTRootView initWithURLstarts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using[RCTRootView alloc] initWithURL, useRCTBridge initWithBundleURLto create a bridge and then useRCTRootView initWithBridge.
First import the React library.
import React
The
initialPropertiesare here for illustration purposes so we have some data for our high score screen. In our React Native component, we will usethis.propsto get access to that data.
@IBAction func highScoreButtonTapped(sender : UIButton) {
NSLog("Hello")
let jsCodeLocation = NSURL(string: "http://localhost:8081/index.ios.bundle?platform=ios")
let mockData:NSDictionary = ["scores":
[
["name":"Alex", "value":"42"],
["name":"Joel", "value":"10"]
]
]
let rootView = RCTRootView(
bundleURL: jsCodeLocation,
moduleName: "RNHighScores",
initialProperties: mockData as [NSObject : AnyObject],
launchOptions: nil
)
let vc = UIViewController()
vc.view = rootView
self.presentViewController(vc, animated: true, completion: nil)
}
Note that
RCTRootView bundleURLstarts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of usingRCTRootView bundleURL, useRCTBridge initWithBundleURLto create a bridge and then useRCTRootView initWithBridge.
When moving your app to production, the
NSURLcan point to a pre-bundled file on disk via something like[[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];. You can use thereact-native-xcode.shscript innode_modules/react-native/packager/to generate that pre-bundled file.
When moving your app to production, the
NSURLcan point to a pre-bundled file on disk via something likelet mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle"). You can use thereact-native-xcode.shscript innode_modules/react-native/packager/to generate that pre-bundled file.
Wire Up
Wire up the new link in the main menu to the newly added event handler method.
One of the easier ways to do this is to open the view in the storyboard and right click on the new link. Select something such as the
Touch Up Insideevent, drag that to the storyboard and then select the created method from the list provided.
Test Your Integration
You have now done all the basic steps to integrate React Native with your current application. Now we will start the React Native packager to build the index.ios.bundle packager and the server running on localhost to serve it.
App Transport Security
Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
Run the Packager
# From the root of your project, where the `node_modules` directory is located.
$ npm start
Run the App
If you are using Xcode or your favorite editor, build and run your native iOS application as normal. Alternatively, you can run the app from the command line using:
# From the root of your project
$ react-native run-ios
In our sample application, you should see the link to the "High Scores" and then when you click on that you will see the rendering of your React Native component.
Here is the native application home screen:
Here is the React Native high score screen:
If you are getting module resolution issues when running your application please see this GitHub issue for information and possible resolution. This comment seemed to be the latest possible resolution.
See the Code
You can examine the code that added the React Native screen on GitHub.
You can examine the code that added the React Native screen on GitHub.
Add JS to your app
In your app's root folder, run:
$ npm init
$ npm install --save react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
This creates a node module for your app and adds the react-native npm dependency. Now open the newly created package.json file and add this under scripts:
"start": "node node_modules/react-native/local-cli/cli.js start"
Copy & paste the following code to index.android.js in your root folder — it's a barebones React Native app:
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class HelloWorld extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.hello}>Hello, World</Text>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
Prepare your current app
In your app's build.gradle file add the React Native dependency:
compile "com.facebook.react:react-native:+" // From node_modules
In your project's build.gradle file add an entry for the local React Native maven directory:
allprojects {
repositories {
...
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/node_modules/react-native/android"
}
}
...
}
Next, make sure you have the Internet permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.
Add native code
You need to add some native code in order to start the React Native runtime and get it to render something. To do this, we're going to create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view.
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
A
ReactInstanceManagercan be shared amongst multiple activities and/or fragments. You will want to make your ownReactFragmentorReactActivityand have a singleton holder that holds aReactInstanceManager. When you need theReactInstanceManager(e.g., to hook up theReactInstanceManagerto the lifecycle of those Activities or Fragments) use the one provided by the singleton.
Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager:
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy();
}
}
We also need to pass back button events to React Native:
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn't handle a back press, your invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity.
Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button:
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
That's it, your activity is ready to run some JavaScript code.
Run your app
To run your app, you need to first start the development server. To do this, simply run the following command in your root folder:
$ npm start
Now build and run your Android app as normal (e.g. ./gradlew installDebug). Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:





