Integration with Existing Apps
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 specific steps are different depending on what platform you're targeting.
- Android (Java & Kotlin)
- iOS (Objective-C)
- iOS (Swift)
Key Concepts
The keys to integrating React Native components into your Android application are to:
- Set up the correct directory structure.
- Install the necessary NPM dependencies.
- Adding React Native to your Gradle configuration.
- Writing the TypeScript code for your first React Native screen.
- Integrate React Native with your Android code using a ReactActivity.
- Testing your integration by running the bundler and seeing your app in action.
Using the Community Template
While you follow this guide, we suggest you to use the React Native Community Template as reference. The template contains a minimal Android app and will help you understanding how to integrate React Native into an existing Android app.
Prerequisites
Follow the guide on setting up your development environment and using React Native without a framework to configure your development environment for building React Native apps for Android.
This guide also assumes you're familiar with the basics of Android development such as creating Activities and editing the AndroidManifest.xml
file.
1. Set up directory structure
To ensure a smooth experience, create a new folder for your integrated React Native project, then move your existing Android project to the /android
subfolder.
2. Install NPM dependencies
Go to the root directory and run the following command:
wget https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.75-stable/template/package.json
This will copy the package.json
file from the Community template to your project.
Next, install the NPM packages by running:
- npm
- Yarn
npm install
yarn install
Installation process has created a new /node_modules
folder. This folder stores all the JavaScript dependencies required to build your project.
Add node_modules/
to your .gitignore
file (here the Community default one).
3. Adding React Native to your app
Configuring Gradle
React Native uses the React Native Gradle Plugin to configure your dependencies and project setup.
First, let's edit your settings.gradle
file by adding those lines (as suggested from the Community template):
// Configures the React Native Gradle Settings plugin used for autolinking
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
// If using .gradle.kts files:
// extensions.configure<com.facebook.react.ReactSettingsExtension> { autolinkLibrariesFromCommand() }
includeBuild("../node_modules/@react-native/gradle-plugin")
// Include your existing Gradle modules here.
// include(":app")
Then you need to open your top level build.gradle
and include this line (as suggested from the Community template):
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:7.3.1")
+ classpath("com.facebook.react:react-native-gradle-plugin")
}
}
This makes sure the React Native Gradle Plugin (RNGP) is available inside your project.
Finally, add those lines inside your Applications's build.gradle
file (it's a different build.gradle
file usually inside your app
folder - you can use the Community template file as reference):
apply plugin: "com.android.application"
+apply plugin: "com.facebook.react"
repositories {
mavenCentral()
}
dependencies {
// Other dependencies here
+ // Note: we intentionally don't specify the version number here as RNGP will take care of it.
+ // If you don't use the RNGP, you'll have to specify version manually.
+ implementation("com.facebook.react:react-android")
+ implementation("com.facebook.react:hermes-android")
}
+react {
+ // Needed to enable Autolinking - https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
+ autolinkLibrariesWithApp()
+}
Finally, open your application gradle.properties
files and add the following line (here the Community template file as reference):
+reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
+newArchEnabled=true
+hermesEnabled=true
Configuring your manifest
First, make sure you have the Internet permission in your AndroidManifest.xml
:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication">
</application>
</manifest>
Then you need to enable cleartext traffic in your debug AndroidManifest.xml
:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
+ android:usesCleartextTraffic="true"
+ tools:targetApi="28"
/>
</manifest>
As usual, here the AndroidManifest.xml file from the Community template to use as a reference: main and debug
This is needed as your application will communicate with your local bundler, [Metro][https://metrobundler.dev/], via HTTP.
Make sure you add this only to your debug manifest.
4. Writing the TypeScript Code
Now we will actually modify the native Android application to integrate React Native.
The first bit of code we will write is the actual React Native code for the new screen that will be integrated into our application.
Create a index.js
file
First, create an empty index.js
file in the root of your React Native project.
index.js
is the starting point for React Native applications, and it is always required. It can be a small file that import
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.
Our index.js should look as follows (here the Community template file as reference):
import {AppRegistry} from 'react-native';
import App from './App';
AppRegistry.registerComponent('HelloWorld', () => App);
Create a App.tsx
file
Then, let's create a App.tsx
file. This is a TypeScript file that will contain the React Native component that we will integrate into our Android application.
import React from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
function App(): React.JSX.Element {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode
? Colors.black
: Colors.white,
padding: 24,
}}>
<Text style={styles.title}>Step One</Text>
<Text>
Edit <Text style={styles.bold}>App.tsx</Text> to
change this screen and see your edits.
</Text>
<Text style={styles.title}>See your changes</Text>
<ReloadInstructions />
<Text style={styles.title}>Debug</Text>
<DebugInstructions />
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
title: {
fontSize: 24,
fontWeight: '600',
},
bold: {
fontWeight: '700',
},
});
export default App;
Here the Community template file as reference
5. Integrating with your Android code
We now need to add some native code in order to start the React Native runtime and tell it to render our React components.
Updating your Application class
First, we need to update your Application
class to properly initialize React Native as follows:
- Java
- Kotlin
package <your-package-here>;
import android.app.Application;
+import com.facebook.react.PackageList;
+import com.facebook.react.ReactApplication;
+import com.facebook.react.ReactHost;
+import com.facebook.react.ReactNativeHost;
+import com.facebook.react.ReactPackage;
+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
+import com.facebook.react.defaults.DefaultReactHost;
+import com.facebook.react.defaults.DefaultReactNativeHost;
+import com.facebook.soloader.SoLoader;
+import java.util.List;
-class MainApplication extends Application {
+class MainApplication extends Application implements ReactApplication {
+ @Override
+ public ReactNativeHost getReactNativeHost() {
+ return new DefaultReactNativeHost(this) {
+ @Override
+ protected List<ReactPackage> getPackages() { return new PackageList(this).getPackages(); }
+ @Override
+ protected String getJSMainModuleName() { return "index"; }
+ @Override
+ public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; }
+ @Override
+ protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; }
+ @Override
+ protected Boolean isHermesEnabled() { return BuildConfig.IS_HERMES_ENABLED; }
+ };
+ }
+ @Override
+ public ReactHost getReactHost() {
+ return DefaultReactHost.getDefaultReactHost(getApplicationContext(), getReactNativeHost());
+ }
@Override
public void onCreate() {
super.onCreate();
+ SoLoader.init(this, false);
+ if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
+ DefaultNewArchitectureEntryPoint.load();
+ }
}
}
// package <your-package-here>
import android.app.Application
+import com.facebook.react.PackageList
+import com.facebook.react.ReactApplication
+import com.facebook.react.ReactHost
+import com.facebook.react.ReactNativeHost
+import com.facebook.react.ReactPackage
+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
+import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
+import com.facebook.react.defaults.DefaultReactNativeHost
+import com.facebook.soloader.SoLoader
-class MainApplication : Application() {
+class MainApplication : Application(), ReactApplication {
+ override val reactNativeHost: ReactNativeHost =
+ object : DefaultReactNativeHost(this) {
+ override fun getPackages(): List<ReactPackage> = PackageList(this).packages
+ override fun getJSMainModuleName(): String = "index"
+ override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
+ override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
+ override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
+ }
+ override val reactHost: ReactHost
+ get() = getDefaultReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
+ SoLoader.init(this, false)
+ if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
+ load()
+ }
}
}
As usual, here the MainApplication.kt Community template file as reference
Creating a ReactActivity
Finally, we need to create a new Activity
that will extend ReactActivity
and host the React Native code. This activity will be responsible for starting the React Native runtime and rendering the React component.
- Java
- Kotlin
// package <your-package-here>;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;
public class MyReactActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "HelloWorld";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new DefaultReactActivityDelegate(this, getMainComponentName(), DefaultNewArchitectureEntryPoint.getFabricEnabled());
}
}
// package <your-package-here>
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MyReactActivity : ReactActivity() {
override fun getMainComponentName(): String = "HelloWorld"
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
As usual, here the MainActivity.kt Community template file as reference
Whenever you create a new Activity, you need to add it to your AndroidManifest.xml
file. You also need set the theme of MyReactActivity
to Theme.AppCompat.Light.NoActionBar
(or to any non-ActionBar theme) as otherwise your application will render an ActionBar on top of your React Native screen:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication">
+ <activity
+ android:name=".MyReactActivity"
+ android:label="@string/app_name"
+ android:theme="@style/Theme.AppCompat.Light.NoActionBar">
+ </activity>
</application>
</manifest>
Now your activity is ready to run some JavaScript code.
6. Test your integration
You have now done all the basic steps to integrate React Native with your current application. Now we will start the Metro bundler to build the TypeScript code of your application and have the server running on localhost to serve it.
First, you need to create a metro.config.js
file in the root of your project as follows:
const {getDefaultConfig} = require('@react-native/metro-config');
module.exports = getDefaultConfig(__dirname);
You can checkout the metro.config.js file from the Community template file as reference.
Once you have the config file in place, you can run the bundler. Run the following command in the root directory of your project:
- npm
- Yarn
npm start
yarn start
Now build and run your Android app as normal.
Once you reach your React-powered Activity inside the app, it should load the JavaScript code from the development server and display:
Creating a release build in Android Studio
You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.
The React Native Gradle Plugin will take care of bundling the JS code inside your APK/App Bundle.
If you're not using Android Studio, you can create a release build with:
cd android
# For a Release APK
./gradlew :app:assembleRelease
# For a Release AAB
./gradlew :app:bundleRelease
Now what?
At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.
Key Concepts
The keys to integrating React Native components into your iOS application are to:
- Set up React Native dependencies and directory structure.
- Understand what React Native components you will use in your app.
- Add these components as dependencies using CocoaPods.
- Develop your React Native components in JavaScript.
- Add a
RCTRootView
to your iOS app. This view will serve as the container for your React Native component. - Start the React Native server and run your native application.
- Verify that the React Native aspect of your application works as expected.
Prerequisites
Follow the guide on setting up your development environment and using React Native without a framework to configure your development environment for building React Native apps for iOS.
1. Set up directory structure
To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing iOS project to a /ios
subfolder.
2. Install JavaScript dependencies
Go to the root directory for your project and create a new package.json
file with the following contents:
{
"name": "MyReactNativeApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "yarn react-native start"
}
}
Next, make sure you have installed the yarn package manager.
Install the react
and react-native
packages. Open a terminal or command prompt, then navigate to the directory with your package.json
file and run:
- npm
- Yarn
npm install react-native
yarn add react-native
This will print a message similar to the following (scroll up in the installation command output to see it):
warning "
react-native@0.52.2
" has unmet peer dependency "react@16.2.0
".
This is OK, it means we also need to install React:
- npm
- Yarn
npm install react@version_printed_above
yarn add react@version_printed_above
Installation process has created a new /node_modules
folder. This folder stores all the JavaScript dependencies required to build your project.
Add node_modules/
to your .gitignore
file.
3. Install CocoaPods
CocoaPods is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.
We recommend installing CocoaPods using Homebrew.
brew install cocoapods
It is technically possible not to use CocoaPods, but that would require manual library and linker additions that would overly complicate this process.
Adding React Native to your app
Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.
Command Line Tools for Xcode
Install the Command Line Tools. Choose Settings... (or Preferences...) in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.
Configuring CocoaPods dependencies
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. We will use CocoaPods to specify which of these "subspecs" your app will depend on.
The list of supported subspec
s is available 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
.
You can specify which subspec
s your app will depend on in a Podfile
file. The easiest way to create a Podfile
is by running the CocoaPods init
command in the /ios
subfolder of your project:
pod init
The Podfile
will contain a boilerplate setup that you will tweak for your integration purposes.
The
Podfile
version changes depending on your version ofreact-native
. Refer to https://react-native-community.github.io/upgrade-helper/ for the specific version ofPodfile
you should be using.
Ultimately, your 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 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
pod 'React', :path => '../node_modules/react-native/'
pod 'React-Core', :path => '../node_modules/react-native/'
pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'
pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"
pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end
After you have created your Podfile
, you are ready to install the React Native pod.
$ pod install
You should see output such as:
Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Downloading dependencies
Installing React (0.62.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 this fails with errors mentioning
xcrun
, make sure that in Xcode in Settings... (or Preferences...) > Locations the Command Line Tools are assigned.
Code integration
Now we will actually modify the native iOS application to integrate React Native. For our 2048 sample 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.
1. Create a index.js
file
First, create an empty index.js
file in the root of your React Native project.
index.js
is the starting point for React Native applications, 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 put everything in index.js
.
2. Add your React Native code
In your index.js
, create your component. In our sample here, we will add a <Text>
component within a styled <View>
import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
const RNHighScores = ({scores}) => {
const contents = 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.js
, you need to add that component to a new or existing ViewController
. The easiest path 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 contain it called RCTRootView
.
1. Create an Event Path
You can add a new link on the main game menu to go to the "High Score" React Native page.
2. 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 Metro bundler to create an index.bundle
that will be served by the React Native server. Inside index.bundle
will be our RNHighScore
module. So, we need to point our RCTRootView
to the location of the index.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.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
header.
#import <React/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 usethis.props
to get access to that data.
- (IBAction)highScoreButtonPressed:(id)sender {
NSLog(@"High Score Button Pressed");
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.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
, useRCTBridge initWithBundleURL
to create a bridge and then useRCTRootView initWithBridge
.
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 thereact-native-xcode.sh
script innode_modules/react-native/scripts/
to generate that pre-bundled file.
3. 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 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 Metro bundler to build the index.bundle
package and the server running on localhost
to serve it.
1. Add App Transport Security exception
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>
App Transport Security is good for your users. Make sure to re-enable it prior to releasing your app for production.
2. Run the packager
To run your app, you need to first start the development server. To do this, run the following command in the root directory of your React Native project:
- npm
- Yarn
npm start
yarn start
3. 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:
- npm
- Yarn
npm run ios
yarn 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.
Now what?
At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.
Key Concepts
The keys to integrating React Native components into your iOS application are to:
- Set up React Native dependencies and directory structure.
- Understand what React Native components you will use in your app.
- Add these components as dependencies using CocoaPods.
- Develop your React Native components in JavaScript.
- Add a
RCTRootView
to your iOS app. This view will serve as the container for your React Native component. - Start the React Native server and run your native application.
- Verify that the React Native aspect of your application works as expected.
Prerequisites
Follow the guide on setting up your development environment and using React Native without a framework to configure your development environment for building React Native apps for iOS.
1. Set up directory structure
To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing iOS project to a /ios
subfolder.
2. Install JavaScript dependencies
Go to the root directory for your project and create a new package.json
file with the following contents:
{
"name": "MyReactNativeApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "yarn react-native start"
}
}
Next, install the react
and react-native
packages. Open a terminal or command prompt, then navigate to the directory with your package.json
file and run:
- npm
- Yarn
npm install react-native
yarn add react-native
This will print a message similar to the following (scroll up in the installation command output to see it):
warning "
react-native@0.52.2
" has unmet peer dependency "react@16.2.0
".
This is OK, it means we also need to install React:
- npm
- Yarn
npm install react@version_printed_above
yarn add react@version_printed_above
Installation process has created a new /node_modules
folder. This folder stores all the JavaScript dependencies required to build your project.
Add node_modules/
to your .gitignore
file.
3. Install CocoaPods
CocoaPods is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.
We recommend installing CocoaPods using Homebrew.
$ brew install cocoapods
It is technically possible not to use CocoaPods, but that would require manual library and linker additions that would overly complicate this process.
Adding React Native to your app
Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.
Command Line Tools for Xcode
Install the Command Line Tools. Choose Settings... (or Preferences...) in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.
Configuring CocoaPods dependencies
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. We will use CocoaPods to specify which of these "subspecs" your app will depend on.
The list of supported subspec
s is available 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
.
You can specify which subspec
s your app will depend on in a Podfile
file. The easiest way to create a Podfile
is by running the CocoaPods init
command in the /ios
subfolder of your project:
$ pod init
The Podfile
will contain a boilerplate setup that you will tweak for your integration purposes.
The
Podfile
version changes depending on your version ofreact-native
. Refer to https://react-native-community.github.io/upgrade-helper/ for the specific version ofPodfile
you should be using.
Ultimately, your Podfile
should look something similar to this:
Podfile Template
After you have created your Podfile
, you are ready to install the React Native pod.
$ pod install
You should see output such as:
Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Downloading dependencies
Installing React (0.62.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 this fails with errors mentioning
xcrun
, make sure that in Xcode in Settings... (or Preferences...) > Locations the Command Line Tools are assigned.
If you get a warning such as "The
swift-2048 [Debug]
target overrides theFRAMEWORK_SEARCH_PATHS
build 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 Paths
inBuild Settings
for bothDebug
andRelease
only contain$(inherited)
.
Code integration
Now we will actually modify the native iOS application to integrate React Native. For our 2048 sample 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.
1. Create a index.js
file
First, create an empty index.js
file in the root of your React Native project.
index.js
is the starting point for React Native applications, 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 put everything in index.js
.
2. Add your React Native code
In your index.js
, create your component. In our sample here, we will add a <Text>
component within a styled <View>
import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
const RNHighScores = ({scores}) => {
const contents = 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.js
, you need to add that component to a new or existing ViewController
. The easiest path 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 contain it called RCTRootView
.
1. Create an Event Path
You can add a new link on the main game menu to go to the "High Score" React Native page.
2. 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 Metro bundler to create an index.bundle
that will be served by the React Native server. Inside index.bundle
will be our RNHighScore
module. So, we need to point our RCTRootView
to the location of the index.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.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 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 usethis.props
to get access to that data.
@IBAction func highScoreButtonTapped(sender : UIButton) {
NSLog("Hello")
let jsCodeLocation = URL(string: "http://localhost:8081/index.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.present(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 usingRCTRootView bundleURL
, useRCTBridge initWithBundleURL
to create a bridge and then useRCTRootView initWithBridge
.
When moving your app to production, the
NSURL
can point to a pre-bundled file on disk via something likelet mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle")
. You can use thereact-native-xcode.sh
script innode_modules/react-native/scripts/
to generate that pre-bundled file.
3. 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 Inside
event, drag that to the storyboard and then select the created method from the list provided.
3. Window Reference
Add an window reference to your AppDelegate.swift file. Ultimately, your AppDelegate should look something similar to this:
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
// Add window reference
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
....
}
Test your integration
You have now done all the basic steps to integrate React Native with your current application. Now we will start the Metro bundler to build the index.bundle
package and the server running on localhost
to serve it.
1. Add App Transport Security exception
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>
App Transport Security is good for your users. Make sure to re-enable it prior to releasing your app for production.
2. Run the packager
To run your app, you need to first start the development server. To do this, run the following command in the root directory of your React Native project:
- npm
- Yarn
npm start
yarn start
3. 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 following command from the root directory of your React Native project:
- npm
- Yarn
npm run ios
yarn 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.
Now what?
At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.