React Native is becoming more popular each day, and it is no surprise: it is used by beginner developers who use JavaScript, but experienced developers also use its components to boost the development speed. While we still believe that apps created with native programming languages are more robust, adding React can be a great help, if you need an app fast.

Why use React Native?

According to studies, mostly mobile app developers prefer to use native tools like Kotlin or Objective-C to build their apps.

react native
While most of developers prefer to code in native languages, React Native is becoming more popular each day, backed up with Facebook and a huge community

However, in some situations React Native is a great solution. For example, imagine you already have an iOS app. To develop the same for Android, you can save loads of time by creating it on React Native for both platforms.

React also works great with native code. Facebook is a great example of it. Now let’s talk in more detail about React and React Native.

What is React?

React, also known as ReactJS or React.js, is a JavaScript library for creating UI. Facebook maintains it and, thanks to the community they’ve built around it, React’s popularity has skyrocketed.

According to the State of JavaScript 2017 study, React is the most popular library out there.

react library for mobile apps
React is the most popular library for building mobile applications, according to the survey

React is used to develop single-page and mobile applications, but if the app is more complex you’ll need additional libraries for APIs, state management, and routing. React is

  • declarative, meaning that is renders components immediately according to your input so that you can see what you’re coding instantly;
  • component-based, allowing you to build self-managing components that you can use across your app;
  • flexible, allowing you to develop features and change the app without having to rewrite what you’ve already created.

What is React Native?

React Native uses React to build native apps. Instead of web components, it uses native Android and iOS components, allowing you to create mobile UIs with declarative components. Basically, React Native works the same way as React, but instead of the Virtual DOM it uses native views to manipulate the DOM.

React Native supports these operating system versions:

  • Android 4.1 (API 16) and higher
  • iOS 8.0 and higher

React Native relies fully on JavaScript and uses Bridge to connect with the native platform. Making a React Native component and the native platform connect via Bridge is probably the trickiest part of the integration process. Making React Native work for a native app isn’t a simple process, and you’ll need to take lots of things into account if you want to do it.

Сomponents, APIs, and native modules

There are lots of built-in components at your disposal. However, there are also lots of third-party libraries and APIs if you need something more specific.

These are some basic components you can find in React Native:

  • View
  • Text
  • Image
  • Text Input
  • Scroll View

These are components and APIs specific for Android:

  • BackHandler — detects hardware button presses for back navigation
  • DatePickerAndroid — opens the standard Android date picker dialog
  • DrawerLayoutAndroid — renders a DrawerLayout on Android
  • PermissionsAndroid — provides access to the permissions model introduced in Android M
  • ProgressBarAndroid — renders a ProgressBar on Android
  • ToastAndroid — creates an Android Toast alert
  • ViewPagerAndroid — a container that allows you to flip left and right between child views

Note that sometimes your app will need access to an API that React Native doesn’t have a module for. In this case, you’ll need to use real native code and build it yourself.

How to integrate React Native with an existing app

Integrating React Native into an existing application is a great way to increase the speed of development, make more complex apps, and implement the same feature for both iOS and Android simultaneously.

If you’re creating your app from scratch, React Native is the way to go, but it also works great for adding user flows, screens, views, and features to an existing native app.

Here’s what you need to do to integrate React Native components into your Android app:

  1. Set up React Native dependencies and the directory structure.
  2. Develop your React Native components in JavaScript.
  3. Add a ReactRootView to your Android app.
  4. Start the React Native server and run your native app.
  5. Verify that the React Native aspect of the app works as expected.

Step 1: Prerequisite

Set up React Native on your system.
Create React Native App is the easiest way to start building a new React Native app. It lets you start a project without installing or configuring any tools for writing any native code.
You’ll need to have Node v6 or later on your machine. We strongly recommend using npm v3 or v4 or a recent version of Yarn. Create React Native App does not currently work with npm v5 due to bugs in npm.

Install Create React Native App globally:

npm install -g create-react-native-app
or
$ yarn global add create-react-native-app

To create a new app, run:

$ create-react-native-app your-app-name
$ cd your-app-name

This will create a directory called your-app-name inside the working directory you’re currently using. Inside your-app-name, this will generate the initial project structure and install all dependencies.

If you already know React Native, you know that all you’ll find here is JavaScript. There will be no iOS or Android directories. Here are the commands you can run in the directory of your project:

  • npm start — runs your app in development mode with an interactive prompt
  • npm test — runs the jest test runner on your tests (a platform for testing all JavaScript code, including React applications)
  • npm run ios — like npm start, only it also attempts to open your app in the iOS Simulator if you’re on a Mac and have it installed
  • npm run android — like npm start, but also attempts to open your app on a connected Android device or emulator; requires Android build tools
  • npm run eject — starts the process of ejecting from Create React Native App’s build scripts. You’ll be asked a couple of questions about how you’d like to build your project.

Remember that running eject is a permanent action. Use a version control system such as Git so you can revert if necessary. An ejected app will require you to have an Xcode or Android Studio environment set up.

The next step is setting up Android Studio with the latest version of the JDK and choosing your existing Android project.

Step 2: Restructuring the existing project

You don’t need to to this to integrate RN into your project. However, if you need to separate the Android Native and React Native code, you’ll need to restructure your project. Here’s how you do it.

Create a folder titled android inside the root directory of the existing project (in the YourAndroidApp folder).
After that, move your Android Native code to the android folder by cutting and pasting. So the existing project files will live at the path /YourAndroidApp/android/.

Now that your Android Native code has been placed in /YourAndroidApp/android, open it in Android Studio.

Install JavaScript dependencies

Move back to the root directory /YourAndroidApp and create a file named package.json and paste the following code inside it:

{
  "name": "YourAndroidApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  }
}

Next, make sure you have the yarn package manager installed.

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:

$ yarn add react-native

If you see a message similar to the following (scroll up in the yarn output to see it), don’t worry:
warning «react-native@0.52.2» has unmet peer dependency «react@16.2.0»

This is okay. It just means you also need to install React:

$ yarn add react@version_printed_above

Yarn 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.

Step 4: Integrating React Native into the project

Add the React Native dependency to your app’s build.gradle file:

dependencies {
    ...
    compile "com.facebook.react:react-native:+" // From node_modules
}

Add an entry for the local React Native maven directory to build.gradle. Be sure to add it to the «allprojects» block and add it to android/build.gradle, not to android/app/build.gradle

allprojects {
    repositories {
        maven {
            url "/YourAndroidApp/node_modules/react-native/android"
        }
        ...
    }
    ...
}

Make sure that the path is correct!

Step 5: Adding permissions

Open AndroidManifest.xml, which can be located at the path android/app/src/main/AndroidManifest.xml, in Android Studio. Add the following permission to it:

<uses-permission android:name="android.permission.INTERNET" />

Step 6: React Native code

Create an index.android.js file inside the root directory /YourAndroidApp. This is the entry point for the React Native app.

ReactRootView

Add some native code and make it render the JS component — this will start RN runtime. Create an Activity (AppCompatActivity) and start an React app inside the ReactRootView that will be created automatically. This app will be set as the main content view.

Create the new Activity with Android Studio and call it MyReactActivity. Then add this:

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")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // The string here (e.g. "YourAndroidApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "YourAndroidApp", null);

        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }
}

You’ll get a lot of errors after pasting this code inside MyReactActivity, as the packages used inside the activity aren’t imported. Pay attention to what BuildConfig you use: it needs to go from your package, not from facebook’s one.

After you made sure everything is correct, you must set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar inside AndroidManifest.xml. This is important, as some React Native UI components rely on it.

After this pass some activity lifecycle callbacks to the ReactInstanceManager and ReactRootView:


@Override
protected void onPause() {
    super.onPause();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostPause(this);
    }
}

@Override
protected void onResume() {
    super.onResume();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostResume(this, this);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostDestroy(this);
    }
    if (mReactRootView != null) {
        mReactRootView.unmountReactApplication();
    }
}

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 the back button press, the invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity.

Step 7: Opening the React App

Next, we need to add logic for opening the MyReactNative activity to launch the React Native app according to the business logic of your app.

Intent intent = new Intent(this, MyReactActivity.class);
startActivity(intent);

To run your app, you need to first start the development server. To do this, simply run the following command inside the root directory /YourAndroidApp:

$ yarn start
//or
$ npm start

Now, run the app from Android Studio as usual and test it out.

Conclusion

React Native components can save the day for your application if you need to integrate something quickly and create one feature for both Android and iOS simultaneously. This framework is constantly being updated, and the community around it is growing every day.

We believe that building native apps with native tools and programming languages is the best and most reliable way to create a high-quality product, but sometimes time to market is more important. That’s why you may find this solution is right for you, though connecting React Native components with native apps can be tricky.

If you have any issues with creating your native app with React Native, don’t hesitate to contact us for a consultation.

Ecommerce development services

Are you planning to expand your business online? We will translate your ideas into intelligent and powerful ecommerce solutions.

Get a Free Consultation!
Request Callback

Request Callback

+