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 Android application are to:
- Understand what React Native components you want to integrate.
react-nativein your Android application root directory to create
mavenpointing to the
- Create a custom React Native specific
Activitythat creates a
- Start the React Native server and run your native application.
- Optionally add more React Native components.
- Prepare for deployment.
- Deploy and Profit!
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.
In your app’s root folder, run:
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
Copy & paste the following code to
index.android.js in your root folder — it’s a barebones React Native app:
In your app’s
build.gradle file add the React Native dependency:
In your project’s
build.gradle file add an entry for the local React Native maven directory:
Next, make sure you have the Internet permission in your
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.
ReactInstanceManagercan be shared amongst multiple activities and/or fragments. You will want to make your own
ReactActivityand have a singleton holder that holds a
ReactInstanceManager. When you need the
ReactInstanceManager(e.g., to hook up the
ReactInstanceManagerto 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
We also need to pass back button events to React Native:
invokeDefaultOnBackPressed method will be called. By default this simply finishes your
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:
To run your app, you need to first start the development server. To do this, simply run the following command in your root folder:
Now build and run your Android app as normal (e.g.