Since React makes no assumptions about the rest of your technology stack, it's easily embeddable within an existing non-React Native app.
In your app's build.gradle
file add the React Native dependency:
You can find the latest version of the react-native library on Maven Central. Next, make sure you have the Internet permission in your AndroidManifest.xml
:
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.
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.
Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager
:
We also need to pass back button events to React Native:
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:
That's it, your activity is ready to run some JavaScript code.
In your project'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 scripts
:
Copy & paste the following code to index.android.js
in your root folder — it's a barebones React Native 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:
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:
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.