Create Existing App Integration Tutorial

Summary:
We currently have iOS and Android existing app integration guides. I have revamped these into a single tutorial, with three sections: Objective-C, Swift and Android.

For Objective-C and and Swift, the tutorial is now based on a more real world app - integrating a React Native-based high score screen into a 2048 app.

For expediency to get the iOS stuff out, for Android, *for now*, I have kept the existing documentation (with minor updates), but am planning to try to follow the same 2048 model for it as well.

This uses the same toggler as Getting Started

> I do note the copypasta of the toggler code. I am planning another separate pull request to make that more modular and reusable across all areas of the documentation on which it seems reasonable.

<img width="1277" alt="screenshot 2016-05-25 15 34 27" src="https://cloud.githubusercontent.com/assets/3757713/15558448/13c0aa1a-228f-11e6-9f38-5117d5824b84.png">
<img width="1260" alt="screenshot 2016-05-25 15 40 50" src="https://cloud.githubusercont
Closes https://github.com/facebook/react-native/pull/7764

Differential Revision: D3444455

Pulled By: JoelMarcey

fbshipit-source-id: 73dcdadd912177bb83b29099ff857046bf495939
This commit is contained in:
Joel Marcey 2016-06-16 08:24:07 -07:00 committed by Facebook Github Bot 7
parent c94e939919
commit 0c4147ac6a
11 changed files with 776 additions and 430 deletions

View File

@ -1,199 +0,0 @@
---
id: embedded-app-android
title: Integrating with Existing Apps
layout: docs
category: Guides (Android)
permalink: docs/embedded-app-android.html
next: signed-apk-android
---
Since React makes no assumptions about the rest of your technology stack, it's easily embeddable within an existing non-React Native app.
## Requirements
* an existing, gradle-based Android app
* Node.js, see Getting Started for setup instructions
## Prepare your 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.
```java
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, "MyAwesomeApp", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
```
Next, we need to pass some activity lifecycle callbacks down to the `ReactInstanceManager`:
```java
@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:
```java
@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:
```java
@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.
## 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:
```js
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class MyAwesomeApp 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('MyAwesomeApp', () => MyAwesomeApp);
```
## 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:
![Screenshot](img/EmbeddedAppAndroid.png)
## Sharing a ReactInstance across multiple Activities / Fragments in your app
You can have multiple Activities or Fragments that use the same `ReactInstanceManager`. You'll want to make your own "ReactFragment" or "ReactActivity" and have a singleton "holder" that holds a `ReactInstanceManager`. When you need the `ReactInstanceManager` / hook up the `ReactInstanceManager` to the lifecycle of those Activities or Fragments, use the one provided by the singleton.

View File

@ -1,228 +0,0 @@
---
id: embedded-app-ios
title: Integrating with Existing Apps
layout: docs
category: Guides (iOS)
permalink: docs/embedded-app-ios.html
next: communication-ios
---
Since React makes no assumptions about the rest of your technology stack its commonly noted as simply the `V` in `MVC` its easily embeddable within an existing non-React Native app. In fact, it integrates with other best practice community tools like [CocoaPods](http://cocoapods.org/).
## Requirements
- [CocoaPods](http://cocoapods.org/) `gem install cocoapods`
- [Node.js](http://nodejs.org)
- Install **nvm** with [its setup instructions here](https://github.com/creationix/nvm#installation). Then run `nvm install node && nvm alias default node`, which installs the latest version of Node.js and sets up your terminal so you can run it by typing `node`. With nvm you can install multiple versions of Node.js and easily switch between them.
- Install the `react-native` package from npm by running the following command in the root directory of your project:
- `npm install react-native`
At this point you should have the React Native package installed under a directory named `node_modules` as a sibling to your `.xcodeproj` file.
## Install React Native Using CocoaPods
[CocoaPods](http://cocoapods.org/) is a package management tool for iOS/Mac development. We need to use it to download React Native. If you haven't installed CocoaPods yet, check out [this tutorial](http://guides.cocoapods.org/using/getting-started.html).
When you are ready to work with CocoaPods, add the following lines to `Podfile`. If you don't have one, then create it under the root directory of your project.
```ruby
# Depending on how your project is organized, your node_modules directory may be
# somewhere else; tell CocoaPods where you've installed react-native from npm
pod 'React', :path => './node_modules/react-native', :subspecs => [
'Core',
'RCTImage',
'RCTNetwork',
'RCTText',
'RCTWebSocket',
# Add any other subspecs you want to use in your project
]
```
Remember to install all subspecs you need. The `<Text>` element cannot be used without the `RCTText` subspec, for example.
Then install your pods:
```
$ pod install
```
## Create Your React Native App
There are two pieces youll need to set up:
1. The root JavaScript file that will contain your actual React Native app and other components
- Wrapper Objective-C code that will load up your script and create a `RCTRootView` to display and manage your React Native components
First, create a directory for your apps React code and create a simple `index.ios.js` file:
```
$ mkdir ReactComponent
$ touch ReactComponent/index.ios.js
```
Copy & paste following starter code for `index.ios.js` its a barebones React Native app:
```
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red'
}
});
class SimpleApp extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>This is a simple application.</Text>
</View>
)
}
}
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
```
`SimpleApp` will be your **module name**, which will be used later on.
## Add Container View To Your App
You should now add a container view for the React Native component. It can be any `UIView` in your app.
![Container view example](img/EmbeddedAppContainerViewExample.png)
However, let's subclass `UIView` for the sake of clean code. Let's name it `ReactView`. Open up `Yourproject.xcworkspace` and create a new class `ReactView` (You can name it whatever you like :)).
```
// ReactView.h
#import <UIKit/UIKit.h>
@interface ReactView : UIView
@end
```
In a view controller that wants to manage this view, go ahead and add an outlet and wire it up:
```
// ViewController.m
@interface ViewController ()
@property (weak, nonatomic) IBOutlet ReactView *reactView;
@end
```
__NOTE__ For Swift apps there is no need for that.
Here I disabled **AutoLayout** for simplicity. In real production world, you should turn on AutoLayout and setup constraints by yourself.
## Add RCTRootView To Container View
Ready for the most interesting part? Now we shall create the `RCTRootView`, where your React Native app lives.
In `ReactView.m`, we need to first initiate `RCTRootView` with the URI of your `index.ios.bundle`. `index.ios.bundle` will be created by packager and served by React Native server, which will be discussed later on.
```
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
// For production use, this `NSURL` could instead point to a pre-bundled file on disk:
//
// NSURL *jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
//
// To generate that file, run the curl command and add the output to your main Xcode build target:
//
// curl http://localhost:8081/index.ios.bundle -o main.jsbundle
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName: @"SimpleApp"
initialProperties:nil
launchOptions:nil];
```
Then add it as a subview of the `ReactView`.
```
[self addSubview:rootView];
rootView.frame = self.bounds;
```
### Swift apps
Add the following to ReactView.swift file:
```
import UIKit
import React
class ReactView: UIView {
let rootView: RCTRootView = RCTRootView(bundleURL: NSURL(string: "http://localhost:8081/index.ios.bundle?platform=ios"),
moduleName: "SimpleApp", initialProperties: nil, launchOptions: nil)
override func layoutSubviews() {
super.layoutSubviews()
loadReact()
}
func loadReact () {
addSubview(rootView)
rootView.frame = self.bounds
}
}
```
And then make sure your view is added in a ViewContainer or story board file.
## Start Development Server
In root directory, we need to start React Native development server.
```
(JS_DIR=`pwd`/ReactComponent; cd node_modules/react-native; npm run start -- --root $JS_DIR)
```
This command will start up a React Native development server within our CocoaPods dependency to build our bundled script. The `--root` option indicates the root of your React Native apps this will be our `ReactComponent` directory containing the single `index.ios.js` file. This running server will package up the `index.ios.bundle` file accessible via `http://localhost:8081/index.ios.bundle`.
## Update App Transport Security
On iOS 9 and above the app won't be a able to connect over http to localhost unless specifically told so. See this thread for alternatives and instructions: http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http.
It is recommended that you add an App Transport Security exception for `localhost` in your app's `Info.plist` file:
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
```
If you don't do this, you will see the error - `Could not connect to development server.` when connecting to your server over http.
## Compile And Run
Now compile and run your app. You shall now see your React Native app running inside of the `ReactView`.
![Example](img/EmbeddedAppExample.png)
Live reload and all of the debugging tools will work from the simulator. Just make sure that `DEBUG=1` is set under Build Settings -> Preprocessor Macros. If you're using Cocoapods and a custom configuration (that is, not "Debug"), make sure you've specified it to be a debug configuration using the [`xcodeproj` setting](https://guides.cocoapods.org/syntax/podfile.html#xcodeproj) in your Podfile. Also make sure you've got a simple React component totally encapsulated behind an Objective-C `UIView` subclass.
## Conclusion
So under the hood, when `RCTRootView` is initialized, it will try to download, parse and run the bundle file from React Native development server. This means all you need to do is to implement your own container view or view controller for the `RCTRootView` the `RCTRootView` ingests your bundled JS and renders your React components. Bravo!
You can checkout full source code of a sample application [here](https://github.com/hfossli/ReactNativeIntegration).

View File

@ -4,7 +4,7 @@ title: Running On Device
layout: docs
category: Guides (Android)
permalink: docs/running-on-device-android.html
next: embedded-app-android
next: signed-apk-android
---
## Prerequisite: USB Debugging

View File

@ -4,7 +4,7 @@ title: Running On Device
layout: docs
category: Guides (iOS)
permalink: docs/running-on-device-ios.html
next: embedded-app-ios
next: communication-ios
---
Note that running on device requires [Apple Developer account](https://developer.apple.com/register) and provisioning your iPhone. This guide covers only React Native specific topic.

View File

@ -4,7 +4,7 @@ title: Core Components
layout: docs
category: Tutorials
permalink: docs/tutorial-core-components.html
next: sample-application-movies
next: tutorial-integration-with-existing-apps
---
Components are the building blocks for a React Native application. A React Native user interface (UI) is specified by declaring components, possibly nested, and then those components are mapped to the native UI on the targeted platform.

View File

@ -0,0 +1,773 @@
---
id: tutorial-integration-with-existing-apps
title: Integration With Existing Apps
layout: docs
category: Tutorials
permalink: docs/tutorial-integration-with-existing-apps.html
next: sample-application-movies
---
<div class="integration-toggler">
<style>
.integration-toggler a {
display: inline-block;
padding: 10px 5px;
margin: 2px;
border: 1px solid #05A5D1;
border-radius: 3px;
text-decoration: none !important;
}
.display-platform-objc .integration-toggler .button-objc,
.display-platform-swift .integration-toggler .button-swift,
.display-platform-android .integration-toggler .button-android {
background-color: #05A5D1;
color: white;
}
block { display: none; }
.display-platform-objc .objc,
.display-platform-swift .swift,
.display-platform-android .android {
display: block;
}</style>
<span>Platform:</span>
<a href="javascript:void(0);" class="button-objc" onclick="display('platform', 'objc')">Objective-C</a>
<a href="javascript:void(0);" class="button-swift" onclick="display('platform', 'swift')">Swift</a>
<a href="javascript:void(0);" class="button-android" onclick="display('platform', 'android')">Android</a>
</div>
<block class="android" />
> 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.
<block class="objc swift android" />
## 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.
<block class="objc swift" />
The keys to integrating React Native components into your iOS application are to:
1. Understand what React Native components you want to integrate.
2. Create a `Podfile` with `subspec`s for all the React Native components you will need for your integration.
3. Create your actual React Native components in JavaScript.
4. Add a new event handler that creates a `RCTRootView` that points to your React Native component and its `AppRegistry` name that you defined in `index.ios.js`.
5. Start the React Native server and run your native application.
6. Optionally add more React Native components.
7. [Debug](/react-native/releases/next/docs/debugging.html).
8. Prepare for [deployment](/react-native/docs/running-on-device-ios.html) (e.g., via the `react-native-xcode.sh` script).
9. Deploy and Profit!
<block class="android" />
The keys to integrating React Native components into your iOS application are to:
1. Understand what React Native components you want to integrate.
2. Install `react-native` in your Android application root directory to create `node_modules/` directory.
3. Create your actual React Native components in JavaScript.
4. Add `com.facebook.react:react-native:+` and a `maven` pointing to the `react-native` binaries in `node_nodules/` to your `build.gradle` file.
4. Create a custom React Native specific `Activity` that creates a `ReactRootView`.
5. Start the React Native server and run your native application.
6. Optionally add more React Native components.
7. [Debug](/react-native/releases/next/docs/debugging.html).
8. [Prepare](/react-native/releases/next/docs/signed-apk-android.html) for [deployment](/react-native/docs/running-on-device-android.html).
9. Deploy and Profit!
<block class="objc swift android" />
## Prerequisites
<block class="android" />
The [Android Getting Started guide](/react-native/docs/getting-started.html) will install the appropriate prerequisites (e.g., `npm`) for React Native on the Android target platform and your chosen development environment.
<block class="objc swift" />
### General
First, follow the [Getting Started guide](/react-native/docs/getting-started.html) for your development environment and the iOS target platform to install the prerequisites for React Native.
### CocoaPods
[CocoaPods](http://cocoapods.org) 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.
```bash
$ 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
<block class="objc" />
Assume the [app for integration](https://github.com/JoelMarcey/iOS-2048) 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.
<block class="swift" />
Assume the [app for integration](https://github.com/JoelMarcey/swift-2048) 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.
<block class="objc swift" />
![Before RN Integration](img/react-native-existing-app-integration-ios-before.png)
## 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 like `ios/` 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](https://github.com/facebook/react/releases) and [React Native](https://github.com/facebook/react/releases) will be sufficient.
<block class="objc" />
```bash
{
"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"
}
}
```
<block class="swift" />
```bash
{
"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"
}
}
```
<block class="objc swift" />
### 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.
```bash
# 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](#package-dependencies). 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 `subspec`s 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 `subspec`s are in [`node_modules/react-native/React.podspec`](https://github.com/facebook/react-native/blob/master/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:
```bash
## 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:
<block class="objc" />
```
# 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
```
<block class="swift" />
```
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
```
<block class="objc swift" />
#### Pod Installation
After you have created your `Podfile`, you are ready to install the React Native pod.
```bash
$ pod install
```
Your should see output such as:
```bash
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.
```
<block class="swift" />
> If you get a warning such as "*The `swift-2048 [Debug]` target overrides the `FRAMEWORK_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig`. This can lead to problems with the CocoaPods installation*", then make sure the `Framework Search Paths` in `Build Settings` for both `Debug` and `Release` only contain `$(inherited)`.
<block class="objc swift" />
## 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.js` is the starting point for React Native applications on iOS. And it is always required. It can be a small file that `require`s 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 in `index.ios.js`
```bash
# 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>`
```js
'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);
```
> `RNHighScores` is 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 Path](img/react-native-add-react-native-integration-link.png)
#### 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](#the-react-native-component) when writing the code for our React Native component.
<block class="objc" />
First `import` the `RCTRootView` library.
```
#import "RCTRootView.h"
```
> The `initialProperties` are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use `this.props` to 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 initWithURL` starts 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`, use [`RCTBridge initWithBundleURL`](https://github.com/facebook/react-native/blob/master/React/Base/RCTBridge.h#L93) to create a bridge and then use `RCTRootView initWithBridge`.
<block class="swift" />
First `import` the `React` library.
```
import React
```
> The `initialProperties` are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use `this.props` to 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 bundleURL` starts 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 bundleURL`, use [`RCTBridge initWithBundleURL`](https://github.com/facebook/react-native/blob/master/React/Base/RCTBridge.h#L93) to create a bridge and then use `RCTRootView initWithBridge`.
<block class="objc" />
> When moving your app to production, the `NSURL` can point to a pre-bundled file on disk via something like `[[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];`. You can use the `react-native-xcode.sh` script in `node_modules/react-native/packager/` to generate that pre-bundled file.
<block class="swift" />
> When moving your app to production, the `NSURL` can point to a pre-bundled file on disk via something like `let mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle")`. You can use the `react-native-xcode.sh` script in `node_modules/react-native/packager/` to generate that pre-bundled file.
<block class="objc swift" />
#### Wire Up
Wire up the new link in the main menu to the newly added event handler method.
![Event Path](img/react-native-add-react-native-integration-wire-up.png)
> 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 Inside` event, 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.
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
```
### Run the Packager
```bash
# 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:
```bash
# 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:
![Home Screen](img/react-native-add-react-native-integration-example-home-screen.png)
Here is the *React Native* high score screen:
![High Scores](img/react-native-add-react-native-integration-example-high-scores.png)
> If you are getting module resolution issues when running your application please see [this GitHub issue](https://github.com/facebook/react-native/issues/4968) for information and possible resolution. [This comment](https://github.com/facebook/react-native/issues/4968#issuecomment-220941717) seemed to be the latest possible resolution.
### See the Code
<block class="objc" />
You can examine the code that added the React Native screen on [GitHub](https://github.com/JoelMarcey/iOS-2048/commit/9ae70c7cdd53eb59f5f7c7daab382b0300ed3585).
<block class="swift" />
You can examine the code that added the React Native screen on [GitHub](https://github.com/JoelMarcey/swift-2048/commit/13272a31ee6dd46dc68b1dcf4eaf16c1a10f5229).
<block class="android" />
## 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:
```js
'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.
```java
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 `ReactInstanceManager` can be shared amongst multiple activities and/or fragments. You will want to make your own `ReactFragment` or `ReactActivity` and have a singleton *holder* that holds a `ReactInstanceManager`. When you need the `ReactInstanceManager` (e.g., to hook up the `ReactInstanceManager` to 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`:
```java
@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:
```java
@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:
```java
@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:
![Screenshot](img/EmbeddedAppAndroid.png)
<script>
// Convert <div>...<span><block /></span>...</div>
// Into <div>...<block />...</div>
var blocks = document.getElementsByTagName('block');
for (var i = 0; i < blocks.length; ++i) {
var block = blocks[i];
var span = blocks[i].parentNode;
var container = span.parentNode;
container.insertBefore(block, span);
container.removeChild(span);
}
// Convert <div>...<block />content<block />...</div>
// Into <div>...<block>content</block><block />...</div>
blocks = document.getElementsByTagName('block');
for (var i = 0; i < blocks.length; ++i) {
var block = blocks[i];
while (block.nextSibling && block.nextSibling.tagName !== 'BLOCK') {
block.appendChild(block.nextSibling);
}
}
function display(type, value) {
var container = document.getElementsByTagName('block')[0].parentNode;
container.className = 'display-' + type + '-' + value + ' ' +
container.className.replace(RegExp('display-' + type + '-[a-z]+ ?'), '');
console.log(container.className);
event && event.preventDefault();
}
// If we are coming to the page with a hash in it (i.e. from a search, for example), try to get
// us as close as possible to the correct platform and dev os using the hashtag and block walk up.
var foundHash = false;
if (window.location.hash !== '' && window.location.hash !== 'content') { // content is default
var hashLinks = document.querySelectorAll('a.hash-link');
for (var i = 0; i < hashLinks.length && !foundHash; ++i) {
if (hashLinks[i].hash === window.location.hash) {
var parent = hashLinks[i].parentElement;
while (parent) {
if (parent.tagName === 'BLOCK') {
var targetPlatform = null;
// Could be more than one target platform, but just choose some sort of order
// of priority here.
// Target Platform
if (parent.className.indexOf('objc') > -1) {
targetPlatform = 'objc';
} else if (parent.className.indexOf('swift') > -1) {
targetPlatform = 'swift';
} else if (parent.className.indexOf('android') > -1) {
targetPlatform = 'android';
} else {
break; // assume we don't have anything.
}
// We would have broken out if both targetPlatform and devOS hadn't been filled.
display('platform', targetPlatform);
foundHash = true;
break;
}
parent = parent.parentElement;
}
}
}
}
// Do the default if there is no matching hash
if (!foundHash) {
var isMac = navigator.platform === 'MacIntel';
display('platform', isMac ? 'objc' : 'android');
}
</script>

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB