Preparing React Native App for Android Release on Mac

When your React Native Application is ready for release to the Android Platform, you need to perform the following steps to create the .aab file or Android App Bundle which contains your compiled code and resources and you can upload to the Play Store. The APK generation and signing is done by Google Play.

I’m using React Native 0.62.2 for this post in VS Code.

Open Terminal and check the Java Home Path:

/usr/libexec/java_home

cd to the path displayed as shown in the image.

Run the keytool command as shown using sudo to generate the keystore and alias as shown below:

sudo keytool -genkey -v -keystore some-helper-key.keystore -alias some-helper-key-alias -keyalg RSA -keysize 2048 -validity 10000

As shown in the screen-shot, answer the questions that pop and your keystore will be generated under the Java Home folder.

Copy that keystore file and paste it in your Android folder under app in your React Native Project.

Modify the android/gradle.properties file and add:

MYAPP_UPLOAD_STORE_FILE=some-helper-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=some-helper-key-alias
MYAPP_UPLOAD_STORE_PASSWORD=***
MYAPP_UPLOAD_KEY_PASSWORD=***

You might not want to store the passwords directly in the above configuration and store them in the keychain Access App, then the last 2 password configs are not required.

Add the Release signingconfig section to the android/app/build.gradle file:

signingConfigs {
        debug {
            .....
        }
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }

cd to the Android folder and run:

./gradlew bundleRelease

The .aab file is generated as: android/app/build/outputs/bundle/release/app-release.aab

Now this is ready to be uploaded to the Play Store.

Issues Faced:

Resource and asset merger: Duplicate resources

The above error occurred for files under drawable folder, app.json, node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons.json etc.

Go to android/app/src/main/res and delete all the directories starting with drawables and the above mentioned .json files. Do not delete the raw folder if it contains any resources.

If you want to directly test the Release version on your device, run the following command under Root folder of the Project:

react-native run-android --variant=release

You can install bundle tool on Mac:

brew install bundletool

To extract the APK directly from the .aab file, run the following commands:

bundletool build-apks --bundle=/MyApp/my_app.aab --output=/MyApp/my_app.apks

If you want to test it on a device, then also include the App signing information:

bundletool build-apks --bundle=/MyApp/apprelease.aab --output=/MyApp/my_app.apks
--ks=/MyApp/keystore.jks
--ks-pass=pass:***
--ks-key-alias=MyKeyAlias
--key-pass=pass:***

Please note that the .aab file should not contain hyphen else it’ll give file not found error.

If you want to generate a single Universal apks file, run the below command. Copy the .aab and .keystore files to the folder from where you’ll run bundle tool using terminal:

bundletool build-apks --bundle=MyApp.aab --output=MyApp.apks --mode=universal --ks=my-key.keystore --ks-pass=pass:**** --ks-key-alias=my-key-alias --key-pass=pass:****

Change the extension .apks to .zip and extract the universal.apk file. You can rename this file and transfer it to your Android device for installation.

You can also install the .apks directly to your connected device using bundle tool:

bundletool install-apks --apks=MyApp.apks

Multiple Commands produce error React Native with XCode11

I had earlier installed react-native-vector-icons in my Project and used the below command to link it:

react-native link

The “multiple commands produce” error seems is caused by the new autolinking feature in React Native 0.60 or above – the line use_native_modules! in ios/Podfile means when you do pod install, any pods found in node_modules are automatically linked.

So when you do pod install, links to all font files are added to [CP] Copy Pods Resources. If you previously installed react-native-vector-icons manually by adding the font files to Copy Bundle Resources, you then get a fatal build error similar to this:

Build system information
error: Multiple commands produce '/Users/xxx/Library/Developer/Xcode/DerivedData/Project-dcurwlhxaqikupbgxeiimmauwnpw/Build/Products/Debug-iphonesimulator/MyApp.app/SimpleLineIcons.ttf':

To fix the problem, remove the font files from Copy Bundle Resources, so that they are only in [CP] Copy Pods Resources.

In your Xcode, Select your Project and go to Build Phases and remove the fonts shown below from Copy Bundle Resources:

Google AdMob with react-native-firebase

This post is to document the steps on how I integrated Google AdMob in my React Native Application and how the issues were resolved. My React Native version is 0.62.2.

I’m using react-native-firebase to integrate AdMob for displaying Advertisements. The steps to install react-native-firebase may be different for lower versions of react-native where manual install might be preferred for both iOS and Android builds.

Install the following packages:

npm install @react-native-firebase/app
nvm install @react-native-firebase/admob

Within the root of your React Native Project, add firebase.json file:

{
  "react-native": {
    "admob_android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx",
    "admob_ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx"
  }
}

Before you build the App, you need to add the valid App Ids for both Android and iOS devices. The App Ids can be found in your Google AdMob account while registering the App for iOS/Android. You can create an account here.

Build the Android version with:

react-native run-android

For the iOS version, you need to run “pod install” first inside the iOS folder to install native modules: RNFBAdMob, RNFBApp, and RNVectorIcons and then run:

react-native run-ios

Even after adding the App Ids, my build was giving error for Android build as Execution failed for task ':app:mergeDexDebug' error.

To resolve this, I had to make changes to my build.gradle file under App Sub Folder under the Android folder.

defaultConfig {
        ....
        multiDexEnabled true
    }

dependencies {
    ...
    implementation 'com.android.support:multidex:1.0.3'
}

If your App is targeting children, make sure to set these configuration using setRequestConfiguration:

import admob, { MaxAdContentRating } from '@react-native-firebase/admob';

admob()
  .setRequestConfiguration({
    // Update all future requests suitable for parental guidance
    maxAdContentRating: MaxAdContentRating.PG,

    // Indicates that you want your content treated as child-directed for purposes of COPPA.
    tagForChildDirectedTreatment: true,

    // Indicates that you want the ad request to be handled in a
    // manner suitable for users under the age of consent.
    tagForUnderAgeOfConsent: true,
  })
  .then(() => {
    // Request config successfully set!
  });

There are different types of Ad Units, I’m using Banner Ads for my case. Also, note that you need to create an Ad Unit in Google AdMob account for the specific type of Ad e.g. Banner Ad and that Ad Unit Id is required to be used in your component. You should use the Test Id in your dev environment.

Below is the example Ad Component:

import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { Colors } from 'react-native/Libraries/NewAppScreen';
import { BannerAd, BannerAdSize, TestIds } from '@react-native-firebase/admob';


const AdComp = (props) => {
    const adUnitId = __DEV__ ? TestIds.BANNER : Platform.OS === 'ios' ? 'ca-app-pub-xxxx/xxxx' : 'ca-app-pub-xxxx/xxxx';

    return(
        <View style={{height: '10%', paddingLeft: 20}}>
            <BannerAd 
            unitId={adUnitId}
            size={BannerAdSize.LARGE_BANNER}
            requestOptions={{
              requestNonPersonalizedAdsOnly: true,
            }} />
        </View>
    );
};

export default AdComp;

You May also face metro server related issues like 500 error for which you might need to restart the metro server which made it work.

If you face the error as:

Unable to load script from assets ‘index.android.bundle’

Follow the below steps:

  1. Go to your project directory and check if this folder exists android/app/src/main/assets

If it exists then delete two files viz index.android.bundle and index.android.bundle.meta

ii) If the folder assets doesn’t exist then create the assets directory there.

2. From your root project directory do

cd android
./gradlew clean

3. Finally, navigate back to the root directory and check

If there is only one file i.e. index.js then run following single command

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

If there are two files i.e index.android.js and index.ios.js then run this as a single command

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

How to align array items in a row React Native

There could be a scenario where you’d want to display the elements in your array in a row spaced evenly.

I’ve imported the following object from another file that contains my Array:

export const keyArrays = {
    myArray : ["A", "B", "C", "D", "E", "F", "G"],
    ....
}

The following code snippet shows how the return method in the main App.js component uses a view. The rowContainer class used in the code below will align the array items in a row inside the view and will wrap the items if going out of View’s width.

The following is the stylesheet snippet used in the App.js component:

const styles = StyleSheet.create({
  rowContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    height: 30,
    paddingTop: 5,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: '600',
    fontFamily: 'AvenirNextCyr-Regular',
    color: Colors.white,
    backgroundColor: '#32879d',
  },
});

Setup React-Native for iOS and Android on Mac with VS Code

The very first step to start development in React-Native is to install the right tools to setup the environment correctly. I’m working on MacOS Catalina and I already have Xcode 11 installed on my machine which is one of the pre-requisites to run the iOS App.

Install the following dependencies for React-Native:

NodeJS: https://nodejs.org/en/download/

The recommended way to install Node is using Homebrew from your Terminal:

brew install node

Watchman: In react-native, Watchman watches the source code for any changes and rebuilds them.

brew install watchman

Install XCode from App Store.

Cocoapods: This is the Dependency Manager for iOS & Mac projects.

sudo gem install cocoapods

This requires you to enter system password.

Install Visual Studio Code for Mac from here. You might face issues on Mac OS Catalina to run VS Code due to Notarization requirements. You can check out this post for more details.

Create the folder inside say your Documents folder on your Mac as below:

mkdir Apps

Open VS Code and open New Terminal and type the following command to create a new React-Native App:

react-native init MyApp
cd MyApp
cd ios
pod install

Come back to the MyApp folder and run the below command to run your App in the iOS simulator:

react-native run-ios

This will install and launch the App in your iOS simulator. The first time might be very slow. It might be helpful to launch your simulator beforehand.

Running on Android:

Install the Android Studio from here, which will install the Android SDK and the required emulator. I’m using the Android 10 emulator for Pixel XL.

react-native run-android

Open the MyApp folder in VS Code to make further changes.

Issues

Running the Android App causes issues while launching the Emulator. The error message is: React Native adb reverse ENOENT

Starting with macOS Catalina, your Mac uses zsh as the default login shell and interactive shell. You can make zsh the default in earlier versions of macOS as well.

So on your Mac:

1 – Open your .zshrc file:

open ~/.zshrc

2 – if .zshrc file doesn’t exist, you need to create one & open again(Step 1)

touch ~/.zshrc

3 – Add this to your .zshrc file

export ANDROID_HOME=/Users/<username>/Library/Android/sdk
export PATH=/Users/<username>/Library/Android/sdk/platform-tools:$PATH

4 – Save and close

5 – Compile your changes

source ~/.zshrc

& make sure to restart your terminal.

Run the command in the Terminal and you’ll see something like below if everything is fine:

adb

Android Debug Bridge version 1.0.41

Version 30.0.0-6374843

Installed as /Users/<username>/Library/Android/sdk/platform-tools/adb

You can also run the code in your VS Code Terminal and see the same output.

The path to Android SDK is available in the Configure button -> SDK Manager (at the bottom right) when you launch Android Studio.