Skip to content

Instantly share code, notes, and snippets.

@shiningnicholson95
Created December 9, 2019 03:06
Show Gist options
  • Save shiningnicholson95/5f42cb53a2e71e9b39113790c50bbf22 to your computer and use it in GitHub Desktop.
Save shiningnicholson95/5f42cb53a2e71e9b39113790c50bbf22 to your computer and use it in GitHub Desktop.

Index

1. Installation RNBase

1. Installation RNBase

Following are the installation steps for every features.

  • Versions - react-native: 0.61.4 - react: 16.9.0

Note: Linking is Automatic in react native version > 0.60

Use react-native init "App_name" --version react-native@0.61.4 for creating a react-native app

1.1. React Navigation

Used for Navigating between screens

  • Version 4.0.10

  • Install yarn add react-navigation

  • Dependencies

    yarn add react-native-reanimated react-native-gesture-handler react-native-screens@^1.0.0-alpha.23

  • Android - To finalize installation of react-native-screens for Android, add the following two lines to dependencies section in android/app/build.gradle:

    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'

  • iOS

    • cd ios/ && pod install
  • Add-on packages

    • yarn add react-navigation-stack - used for creating a stack navigator createStackNavigator
  • Files implemented

    • Router.js

1.2. Splash Screen

Screen with app icon for performing mandatory events before app startup

  • Version 3.2.0

  • Install yarn add react-native-splash-screen

  • Linking

    • Android:

      • Automatic
    • iOS:

      1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]

      2. Go to node_modules ➜ react-native-splash-screen and add SplashScreen.xcodeproj

      3. In XCode, in the project navigator, select your project. Add libSplashScreen.a to your project's Build Phases ➜ Link Binary With Libraries

      4. To fix 'RNSplashScreen.h' file not found, you have to select your project → Build Settings → Search Paths → Header Search Paths to add:

        $(SRCROOT)/../node_modules/react-native-splash-screen/ios

  • Plugin Configuration

    • Android

      Update the MainActivity.java to use react-native-splash-screen via the following changes:

      import android.os.Bundle; // here
      import com.facebook.react.ReactActivity;
      // react-native-splash-screen >= 0.3.1
      import org.devio.rn.splashscreen.SplashScreen; // here
      // react-native-splash-screen < 0.3.1
      import com.cboy.rn.splashscreen.SplashScreen; // here
      
      public class MainActivity extends ReactActivity {
        @Override
          protected void onCreate(Bundle savedInstanceState) {
              SplashScreen.show(this);  // here
              super.onCreate(savedInstanceState);
          }
          // ...other code
      }
    • iOS:

      Update AppDelegate.m with the following additions:

       #import "AppDelegate.h"
      
       #import <React/RCTBundleURLProvider.h>
       #import <React/RCTRootView.h>
       #import "RNSplashScreen.h"  // here
      
       @implementation AppDelegate
      
       - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
       {
           // ...other code
      
           [RNSplashScreen show];  // here
           // or
           //[RNSplashScreen showSplash:@"LaunchScreen" inRootView:rootView];
           return YES;
       }
      
       @end
      
  • Usage

    Import react-native-splash-screen in your JS file.

    import SplashScreen from 'react-native-splash-screen'

    • Android

      Create a file called launch_screen.xml in app/src/main/res/layout (create the layout-folder if it doesn't exist). The contents of the file should be the following:

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="match_parent"
          android:layout_height="match_parent">
          <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/launch_screen" android:scaleType="centerCrop" />
      </RelativeLayout>

      Customize your launch screen by creating a launch_screen.png-file and placing it in an appropriate drawable-folder. Android automatically scales drawable, so you do not necessarily need to provide images for all phone densities. You can create splash screens in the following folders:

      • drawable-ldpi
      • drawable-mdpi
      • drawable-hdpi
      • drawable-xhdpi
      • drawable-xxhdpi
      • drawable-xxxhdpi

      Add a color called primary_dark in app/src/main/res/values/colors.xml

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
          <color name="primary_dark">#000000</color>
      </resources>

      Optional steps:

      If you want the splash screen to be transparent, follow these steps.

      Open android/app/src/main/res/values/styles.xml and add <item name="android:windowIsTranslucent">true</item> to the file. It should look like this:

      <resources>
          <!-- Base application theme. -->
          <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
              <!-- Customize your theme here. -->
              <item name="android:windowIsTranslucent">true</item>
          </style>
      </resources>

      To learn more see examples

      If you want to customize the color of the status bar when the splash screen is displayed:

      Create android/app/src/main/res/values/colors.xml and add

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
          <color name="status_bar_color"><!-- Colour of your status bar here --></color>
      </resources>

      Create a style definition for this in android/app/src/main/res/values/styles.xml:

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
          <style name="SplashScreenTheme" parent="SplashScreen_SplashTheme">
              <item name="colorPrimaryDark">@color/status_bar_color</item>
          </style>
      </resources>

      Change your show method to include your custom style:

      SplashScreen.show(this, R.style.SplashScreenTheme);
    • iOS

      Customize your splash screen via LaunchImage or LaunchScreen.xib,

      Learn more to see examples

  • Files implemented

    • Splash.js

1.3. Custom Fonts

To use any font other than react-native provided fonts

  • Setup

    • Download the requried fonts and copy it to ./src/assets/fonts/

    • Create File react-native.config.js and add following code in root project and add following code

      module.exports = {
        project: {
          ios: {},
          android: {}, // grouped into "project"
        },
        assets: ['./src/assets/Fonts/'],
      };
    • use react-native link

    • link command will links fonts in Info.plst for IOS and creates fonts directory android/app/src/main/assets/fonts for Android, where copies your fonts

    • Use it as fontFamily: "OpenSans-Bold" in text style

  • Files implemented

    • RNBaseText.js

1.4. Vector Icons

Used for icons in application

refer https://oblador.github.io/react-native-vector-icons/ for icons catlog

  • Version ^6.6.0

  • Install yarn add react-native-vector-icons

  • Android - To finalize installation of react-native-vector-icons for Android, add the following line at end of file in android/app/build.gradle:

    apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

  • iOS

    • Add following lines in ios/projectname/Info.plist

      <key>UIAppFonts</key>
          <array>
              <string>AntDesign.ttf</string>
              <string>Entypo.ttf</string>
              <string>EvilIcons.ttf</string>
              <string>Feather.ttf</string>
              <string>FontAwesome.ttf</string>
              <string>FontAwesome5_Brands.ttf</string>
              <string>FontAwesome5_Regular.ttf</string>
              <string>FontAwesome5_Solid.ttf</string>
              <string>Foundation.ttf</string>
              <string>Ionicons.ttf</string>
              <string>MaterialCommunityIcons.ttf</string>
              <string>MaterialIcons.ttf</string>
              <string>Octicons.ttf</string>
              <string>SimpleLineIcons.ttf</string>
              <string>Zocial.ttf</string>
          </array>
  • Files implemented

    • VectorIcons.js

1.5. Permissions

Including Customs fonts in react native

  • Version ^6.6.0

  • Install yarn add react-native-permissions

  • iOS

    By default no permission handler is installed. Update your Podfile by choosing the ones you want to check or request, then run pod install.

    # - Ensure that you have installed at least Cocoapods 1.5.0
    # - Replace use_framework! with use_modular_headers!
    # (see http://blog.cocoapods.org/CocoaPods-1.5.0 for more details)
    
    target 'YourAwesomeProject' do
    
      # …
    
      permissions_path = '../node_modules/react-native-permissions/ios'
    
      pod 'Permission-BluetoothPeripheral', :path => "#{permissions_path}/BluetoothPeripheral.podspec"
      pod 'Permission-Calendars', :path => "#{permissions_path}/Calendars.podspec"
      pod 'Permission-Camera', :path => "#{permissions_path}/Camera.podspec"
      pod 'Permission-Contacts', :path => "#{permissions_path}/Contacts.podspec"
      pod 'Permission-FaceID', :path => "#{permissions_path}/FaceID.podspec"
      pod 'Permission-LocationAlways', :path => "#{permissions_path}/LocationAlways.podspec"
      pod 'Permission-LocationWhenInUse', :path => "#{permissions_path}/LocationWhenInUse.podspec"
      pod 'Permission-MediaLibrary', :path => "#{permissions_path}/MediaLibrary.podspec"
      pod 'Permission-Microphone', :path => "#{permissions_path}/Microphone.podspec"
      pod 'Permission-Motion', :path => "#{permissions_path}/Motion.podspec"
      pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications.podspec"
      pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary.podspec"
      pod 'Permission-Reminders', :path => "#{permissions_path}/Reminders.podspec"
      pod 'Permission-Siri', :path => "#{permissions_path}/Siri.podspec"
      pod 'Permission-SpeechRecognition', :path => "#{permissions_path}/SpeechRecognition.podspec"
      pod 'Permission-StoreKit', :path => "#{permissions_path}/StoreKit.podspec"
    
    end

    If you encounter the error Invalid RNPermission X. Should be one of: (), first check that you link at least one permission handler. If you did, try to cleanup Xcode junk data with npx react-native-clean-project --remove-iOS-build --remove-iOS-pods_

    Then update your Info.plist with wanted permissions usage descriptions:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    
      <!--  Keep only the permissions used in your app  -->
    
      <key>NSAppleMusicUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSBluetoothAlwaysUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSBluetoothPeripheralUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSCalendarsUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSCameraUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSContactsUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSFaceIDUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSLocationAlwaysUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSLocationWhenInUseUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSMicrophoneUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSMotionUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSPhotoLibraryUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSRemindersUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSSpeechRecognitionUsageDescription</key>
      <string>YOUR TEXT</string>
      <key>NSSiriUsageDescription</key>
      <string>YOUR TEXT</string>
    
      <!-- … -->
    
    </dict>
    </plist>
  • Android

    Add all wanted permissions to your app android/app/src/main/AndroidManifest.xml file:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.myawesomeapp">
    
      <!--  Keep only the permissions used in your app  -->
    
      <uses-permission android:name="android.permission.ACCEPT_HANDOVER" />
      <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
      <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
      <uses-permission android:name="android.permission.BODY_SENSORS" />
      <uses-permission android:name="android.permission.CALL_PHONE" />
      <uses-permission android:name="android.permission.CAMERA" />
      <uses-permission android:name="android.permission.GET_ACCOUNTS" />
      <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
      <uses-permission android:name="android.permission.READ_CALENDAR" />
      <uses-permission android:name="android.permission.READ_CALL_LOG" />
      <uses-permission android:name="android.permission.READ_CONTACTS" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="android.permission.READ_SMS" />
      <uses-permission android:name="android.permission.RECEIVE_MMS" />
      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.RECEIVE_WAP_PUSH" />
      <uses-permission android:name="android.permission.RECORD_AUDIO" />
      <uses-permission android:name="android.permission.SEND_SMS" />
      <uses-permission android:name="android.permission.USE_SIP" />
      <uses-permission android:name="android.permission.WRITE_CALENDAR" />
      <uses-permission android:name="android.permission.WRITE_CALL_LOG" />
      <uses-permission android:name="android.permission.WRITE_CONTACTS" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" />
    
      <!-- … -->
    
    </manifest>
  • Files implemented

    • PermissionsUtils.js

1.6. WebView

Used for displaying web pages and local html content

  • Version 7.5.1

  • Install yarn add react-native-webview

  • Android

    • Automatic
  • iOS

    • cd ios/ && pod install
  • Files implemented

    • WebView.js

1.7. Network Info

Used for getting the network information.

  • Version 4.6.1

  • Install yarn add @react-native-community/netinfo

  • Android

    • Automatic
  • iOS

    • cd ios/ && pod install
  • Files implemented

    • NetwrokInfo.js

1.8. QR code Scanner

To scan QR codes using mobile Camera

  • Version 1.3.1

  • Install yarn add react-native-qrcode-scanner

  • Requirements

    • iOS

    • With iOS 10 and higher you need to add the "Privacy - Camera Usage Description" key to the info.plist of your project. This should be found in 'your_project/ios/your_project/Info.plist'. Add the following code:

      <key>NSCameraUsageDescription</key>
      <string>Your message to user when the camera is accessed for the first time</string>
      
      <!-- Include this only if you are planning to use the camera roll -->
      <key>NSPhotoLibraryUsageDescription</key>
      <string>Your message to user when the photo library is accessed for the first time</string>
      
      <!-- Include this only if you are planning to use the microphone for video recording -->
      <key>NSMicrophoneUsageDescription</key>
      <string>Your message to user when the microsphone is accessed for the first time</string>
    • Android

      With Android 7 and higher you need to add the "Vibration" permission to your AndroidManifest.xml of your project. This should be found in your android/app/src/main/AndroidManifest.xml Add the following:

      <uses-permission android:name="android.permission.VIBRATE"/>
  • Dependencies

    • Install yarn install react-native-permissions

    • Install yarn install react-native-camera

      • Android Insert the following lines in android/app/build.gradle:

        inside defaultConfig block insert:

        android {
          ...
          defaultConfig {
            ...
            missingDimensionStrategy 'react-native-camera', 'general' <-- insert this line
          }
        }
      • iOS

      1. Add the plugin dependency to your Podfile, pointing at the path where NPM installed it:

        pod 'react-native-camera', path: '../node_modules/react-native-camera'
      2. Run pod install

        Note: You might need to adjust your Podfile following the example below:

        target 'yourTargetName' do
          # See http://facebook.github.io/react-native/docs/integration-with-existing-apps.html#configuring-cocoapods-dependencies
          pod 'React', :path => '../node_modules/react-native', :subspecs => [
            'Core',
            'CxxBridge', # Include this for RN >= 0.47
            'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
            'RCTText',
            'RCTNetwork',
            'RCTWebSocket', # Needed for debugging
            'RCTAnimation', # Needed for FlatList and animations running on native UI thread
            # Add any other subspecs you want to use in your project
          ]
        
          # Explicitly include Yoga if you are using RN >= 0.42.0
          pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
        
          # Third party deps podspec link
          pod 'react-native-camera', path: '../node_modules/react-native-camera'
        
        end
        
        post_install do |installer|
          installer.pods_project.targets.each do |target|
            if target.name == "React"
              target.remove_from_project
            end
          end
        end
  • Files implemented

    • QRCodeScanner.js

1.9. Redux

Global state management tool

  • Version 4.0.4

  • Install yarn add redux

  • Dependencies

    • react-redux
      • version 7.1.3
      • install yarn add react-redux
    • redux-logger
      • version 3.0.6
      • install yarn add redux-logger
    • redux-persist
      • version 1.0.2
      • install yarn add redux-persist
    • redux-thunk
      • version 2.3.0
      • install yarn add redux-thunk
  • Files implemented

    • App.js
    • Store.js
    • ReduxDemo.js

1.10. Firebase Core

Adding Project to Firebase for using firebase features

  • Version 5.5.6
  • Install yarn add react-native-firebase

The first thing you'll need to have is an active Firebase project.

If you already have an existing project you can skip to the Platform Specific Installation section.

  • Creating a new project

    • Visit the Firebase console.

    • Click the Add project box as shown below: Dashboard

    • A dialog will appear as shown below

    • Enter your new project name and modify the project id and region if necessary

    • Click Create Project when finished

    • Your project will now be created - this can take a few seconds

    • Once created click the Continue button

      New Project Dialog

    • Once created you'll be redirected to the project homepage as show below New Project Homepage

Platform Specific Installation

Both Android and iOS require additional installation steps, please follow the platform specific guides bellow:

  • Android

    • Setup google-services.json

      A google-services.json file contains all of the information required by the Firebase Android SDK to connect to your Firebase project. To automatically generate the json file, follow the instructions on the Firebase console to "Add Firebase to your app".

      Once downloaded, place this file in the root of your project at android/app/google-services.json.

      The following instructions are also described on the Firebase console when going through the wizard.

      In order for Android to parse this file, add the google-services gradle plugin as a dependency to your project in the project level build.gradle file:

      buildscript {
        // ...
        dependencies {
          // ...
          classpath 'com.google.gms:google-services:{{ android.gms.google-services }}'
        }
      }

      To apply the plugin to your project, add the following to the VERY BOTTOM of your app android/app/build.gradle file:

      apply plugin: 'com.google.gms.google-services'
    • Add Firebase modules

      The Firebase modules need to be installed as project dependencies. In the android/app/build.gradle file, add the following:

      dependencies {
        // This should be here already
        implementation project(':react-native-firebase')
      
        // Firebase dependencies
        implementation "com.google.android.gms:play-services-base:{{ android.gms.play-services-base }}"
        implementation "com.google.firebase:firebase-core:{{ android.firebase.core }}"
      
        ...
    • Update Gradle

      Due to some breaking changes in v12+ of the Android Firebase libraries, you'll need to upgrade your Gradle version to at least v4.4 and make a few other tweaks as follows:

      1. In android/gradle/wrapper/gradle-wrapper.properties, update the gradle URL to gradle-4.4-all.zip

      2. In android/build.gradle check that you have google() specified in the buildScript repositories section:

        buildscript {
            repositories {
                google()  // <-- Check this line exists and is above jcenter
                jcenter()
                // ...
            }
            // ...
        }
      3. In android/build.gradle update Android build tools to version {{ android.build.tools }}:

        classpath 'com.android.tools.build:gradle:{{ android.build.tools }}'
      4. In android/app/build.gradle update all your compile statements to be implementation, e.g.

        implementation project(':react-native-firebase')
      5. When running your app from within Android Studio, you may encounter Missing Byte Code errors. This is due to a known issue with version 3.1.x of the android tools plugin: here . You'll need to disable Instant Run to get past this error.

    • Update Google Play service maven repository

      Google Play services from 11.2.0 onwards require their dependencies to be downloaded from Google's Maven respository so add the required reference to the repositories section of the project level build.gradle (android/build.gradle):

          allprojects {
              repositories {
                  mavenLocal()
                  google() // <-- Add this line above jcenter
                  jcenter()
                  maven {
                      // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                      url "$rootDir/../node_modules/react-native/android"
                  }
              }
          }
          ```
  • iOS

    1. Firebase Installation

    • 1.1. Setup GoogleService-Info.plist

      A GoogleService-Info.plist file contains all of the information required by the Firebase iOS SDK to connect to your Firebase project. To automatically generate the plist file, follow the instructions on the Firebase console to "Add Firebase to your app".

      Once downloaded, place the file in the root of your iOS app at ios/[YOUR APP NAME]/GoogleService-Info.plist.

      Make sure that the GoogleService-Info.plist file has been added to your project within XCode.

    • 1.2. Initialise Firebase

      The following instructions are also described on the Firebase console when going through the wizard.

      To initilize the native SDK in your app, add the following to your ios/[YOUR APP NAME]/AppDelegate.m file:

      A) At the top of the file:

      #import <Firebase.h>

      B) At the beginning of the didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method add the following line:

      [FIRApp configure];

      ?> It is recommended to add the line within the method BEFORE creating the RCTRootView. Otherwise the initialization can occur after already being required in your JavaScript code - leading to app not initialised exceptions.

    • 1.3. Install Firebase Library

      • Option 1: Cocoapods (Recommended)

        Firebase recommends using Cocoapods to install the Firebase SDK.

        • 1.3.0. If you don't already have Cocoapods set up Follow the instructions to install Cocoapods and create your Podfile here.

          The Podfile needs to be initialised in the ios directory of your project. Make sure to update cocoapods libs first by running pod update

        • Troubleshooting

          1. When running pod install you may encounter an error saying that a tvOSTests target is declared twice. This appears to be a bug with pod init and the way that react native is set up.

            Resolution:

            • Open your Podfile
            • Remove the duplicate tvOSTests target nested within the main project target
            • Re-run pod install.

          2. When running pod install you may encounter a number of warnings relating to target overrides 'OTHER_LDFLAGS'.

            Resolution:

            • Open Xcode
            • Select your project
            • For each target: -- Select the target -- Click Build settings -- Search for other linker flags -- Add $(inherited) as the top line if it doesn't already exist
            • Re-run pod install

          3. When running pod install you may encounter a warning that a default iOS platform has been assigned. If you wish to specify a different minimum version:

            Resolution

            • Open your Podfile
            • Uncomment the # platform :ios, '9.0' line by removing the # character
            • Change the version as required

          4. After installation you encounter an error like RNFirebase core module was not found natively on iOS.

            Resolution

            • It's most likely you did not run pod update to get the latest pod versions
            • Run pod update
            • You should see updated versions of your pods installed
            • You may need to re-run pod install
        • 1.3.1. Check the Podfile platform version

          We recommend using a minimum platform version of at least 9.0 for your application to ensure that the correct version of the Firebase libraries are used. To do this, you need to uncomment or make sure the following line is present at the top of your Podfile:

          platform :ios, '9.0'
        • 1.3.2. Add the required pods

          Simply add the following to your Podfile either at the top level, or within the main project target:

          # Required by RNFirebase
          pod 'Firebase/Core', '~> {{ ios.firebase.core }}'

          Run pod install.

          You need to use the ios/[YOUR APP NAME].xcworkspace instead of the ios/[YOUR APP NAME].xcproj file from now on.

    • Option 2: Manual frameworks (Not Recommended)

      If for some reason you are unable to use Cocoapods, then you need to manually unzip the Firebase SDK to the ios/Firebase folder, and then drag all desired frameworks and Firebase.h to the project (as documented in the README), in order to be picked up by React Native Firebase.

1.11 Crashlytics

  • Android

    • Add the Firebase Crashlytics dependency to android/app/build.gradle:

      dependencies {
        // ...
        implementation('com.crashlytics.sdk.android:crashlytics:{{ android.firebase.crashlytics }}@aar') {
          transitive = true
        }
      }

      Crashlytics also requires the Fabric Gradle dependency. In your projects android/build.gradle file, add the plugin to your dependencies and also check that you have version {{ android.gms.google-services }} of the google-services plugin:

      buildscript {
        // ...
        dependencies {
          // ...
          classpath 'com.google.gms:google-services:{{ android.gms.google-services }}'
          classpath 'io.fabric.tools:gradle:{{ android.fabric.tools }}'
        }
      }

      You need to add maven { url 'https://maven.fabric.io/public' } to your android/build.gradle as follows:

      buildscript {
          repositories {
              jcenter()
              maven {
                  url 'https://maven.fabric.io/public'
              }
          }
          // ...
      }

      At the top of your android/app/build.gradle file, below other plugins, apply the io.fabric plugin:

      apply plugin: "com.android.application"
      apply plugin: "io.fabric"
    • Install the RNFirebase Crashlytics package

      Add the RNFirebaseCrashlyticsPackage to your android/app/src/main/java/com/[app name]/MainApplication.java:

      // ...
      import com.facebook.react.ReactApplication;
      import io.invertase.firebase.fabric.crashlytics.RNFirebaseCrashlyticsPackage; // <-- Add this line
      
      public class MainApplication extends Application implements ReactApplication {
          // ...
      
          @Override
          protected List<ReactPackage> getPackages() {
            @SuppressWarnings("UnnecessaryLocalVariable")
            List<ReactPackage> packages = new PackageList(this).getPackages();
            // Packages that cannot be autolinked yet can be added manually here, for example:
            // packages.add(new MyReactNativePackage());
            packages.add(new RNFirebaseCrashlyticsPackage()); // <-- Add this line
            return packages;
          }
        };
        // ...
      }
  • iOS

    • Pods (recommended)

      • Add the pods

        Add the following to your Podfile:

        pod 'Fabric', '~> {{ ios.fabric.tools }}'
        pod 'Crashlytics', '~> {{ ios.firebase.crashlytics }}'

        Run pod update.

      • Add the Crashlytics run script

      1. Open your project in Xcode and select its project file in the Navigator

      2. Open the Build Phases tab.

      3. Click + Add a new build phase, and select New Run Script Phase.

      4. Add the following line to the Type a script.. text box:

        "${PODS_ROOT}/Fabric/run"

1.12 Analytics

  • Android

    • Add the RNFirebaseAnalyticsPackage to your android/app/src/main/java/com/[app name]/MainApplication.java:

      // ...
      import com.facebook.react.ReactApplication;
      import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; // <-- Add this line
      
      public class MainApplication extends Application implements ReactApplication {
          // ...
      
          @Override
          protected List<ReactPackage> getPackages() {
            @SuppressWarnings("UnnecessaryLocalVariable")
            List<ReactPackage> packages = new PackageList(this).getPackages();
            // Packages that cannot be autolinked yet can be added manually here, for example:
            // packages.add(new MyReactNativePackage());
            packages.add(new RNFirebaseAnalyticsPackage()); // <-- Add this line
            return packages;
          }
        };
        // ...
      }
  • iOS

    • Device Identification

      If you would like to enable Firebase Analytics to generate automatic audience metrics for iOS (as it does by default in Android), you must link additional iOS libraries, as documented by the Google Firebase team. Specifically you need libAdIdAccess.a and AdSupport.framework

      The way to do this using Cocoapods is to add this to your Podfile (though please use the most current Pod version supported by react-native-firebase):

        pod 'GoogleIDFASupport', '~> 3.14.0'

1.13 Cloud Messaging

  • Android

    • Add the dependency

      Add the Firebase Cloud Messaging dependency and optional ShortcutBadger dependency to android/app/build.gradle:

      dependencies {
        // ...
        implementation "com.google.firebase:firebase-messaging:{{ android.firebase.messaging }}"
        implementation 'me.leolin:ShortcutBadger:1.1.21@aar' // <-- Add this line if you wish to use badge on Android
      }
    • Install the RNFirebase Messaging package

      Add the RNFirebaseMessagingPackage to your android/app/src/main/java/com/[app name]/MainApplication.java:

      // ...
      import com.facebook.react.ReactApplication;
      import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line
      
      public class MainApplication extends Application implements ReactApplication {
          // ...
      
          @Override
          protected List<ReactPackage> getPackages() {
            @SuppressWarnings("UnnecessaryLocalVariable")
            List<ReactPackage> packages = new PackageList(this).getPackages();
            // Packages that cannot be autolinked yet can be added manually here, for example:
            // packages.add(new MyReactNativePackage());
            packages.add(new RNFirebaseMessagingPackage()); // <-- Add this line
            return packages;
          }
        };
        // ...
      }
    • Update Android Manifest

      Add the following to android/app/src/main/AndroidManifest.xml:

      Within the application component, add the messaging service:

      <application ...>
      
        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
          <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
          </intent-filter>
        </service>
      
      </application>

      For RNFB versions less than 5.2.0 only; add the instance ID service:

      <application ...>
      
        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
          <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
          </intent-filter>
        </service>
      
      </application>
    • (Optional) Background Messages

      If you want to be able to react to data-only messages when your app is in the background, e.g. to display a heads up notification, then you need to add the following to android/app/src/main/AndroidManifest.xml:

      <application ...>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
      </application>
  • iOS

    • Add the pod

      Add the following to your Podfile:

      pod 'Firebase/Messaging', '~> {{ ios.firebase.messaging }}'

      Run pod update.

    • Setup Certificates

      Please follow the instructions on the Firebase docs on how to setup your APN certificates with FCM.

    • Enable Capabilities

      In Xcode, enable the following capabilities:

      1. Push Notifications
      2. Background modes > Remote notifications
    • Debugging

      If you're having problems with messages not being received, check out the following blog post for help:

      https://firebase.googleblog.com/2017/01/debugging-firebase-cloud-messaging-on.html

1.14 Notifications

  • Android

    • Add the RNFirebaseNotificationsPackage to your android/app/src/main/java/com/[app name]/MainApplication.java:

      // ...
      import com.facebook.react.ReactApplication;
      import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; // <-- Add this line
      
      public class MainApplication extends Application implements ReactApplication {
          // ...
      
          @Override
          protected List<ReactPackage> getPackages() {
            @SuppressWarnings("UnnecessaryLocalVariable")
            List<ReactPackage> packages = new PackageList(this).getPackages();
            // Packages that cannot be autolinked yet can be added manually here, for example:
            // packages.add(new MyReactNativePackage());
            packages.add(new RNFirebaseNotificationsPackage()); // <-- Add this line
            return packages;
          }
        };
        // ...
      }
    • Update Android Manifest

      Add the following to android/app/src/main/AndroidManifest.xml:

      Add permissions:

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

      Set app launch mode inside activity props:

      <activity
        ...
        android:launchMode="singleTop"
      >
    • Default icon and color (Optional)

      Within the application component, add metadata elements to set a default notification icon and color. Android uses these values whenever incoming messages do not explicitly set icon or color.

      <application ...>
        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
            See README(https://goo.gl/l4GJaQ) for more. -->
        <meta-data
          android:name="com.google.firebase.messaging.default_notification_icon"
          android:resource="@drawable/ic_stat_ic_notification" />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
            notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
          android:name="com.google.firebase.messaging.default_notification_color"
          android:resource="@color/colorAccent" />
      </application>
    • Notification channels (Optional)

      From Android 8.0 (API level 26) and higher, notification channels are supported and recommended. FCM provides a default notification channel with basic settings. If you prefer to create and use your own default channel, set default_notification_channel_id to the ID of your notification channel object as shown; FCM will use this value whenever incoming messages do not explicitly set a notification channel.

      <application ...>
        <meta-data
          android:name="com.google.firebase.messaging.default_notification_channel_id"
          android:value="@string/default_notification_channel_id"/>
      </application>
    • Scheduled Notifications (Optional)

      If you would like to schedule local notifications then you also need to add the following to the application component of android/app/src/main/AndroidManifest.xml:

      <application ...>
        <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
        <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
          <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
        </receiver>
      </application>
  • iOS

    • Update AppDelegate.m

      Add the following import to the top of your ios/[App Name]/AppDelegate.m:

      #import "RNFirebaseNotifications.h"

      Add the following to the didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method, right after [FIRApp Configure]:

      [RNFirebaseNotifications configure];

      Add the following method:

      - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
        [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
      }
    • Remote Notifications (Optional)

      If you would like to support Remote Notifications via FCM, also add the following import to the top of your ios/[App Name]/AppDelegate.m:

      #import "RNFirebaseMessaging.h"

      Then add the following methods to your ios/[App Name]/AppDelegate.m:

      - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
                                                            fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
        [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
      }
      
      - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
        [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
      }

1.15 Deep Linking

  • Android

    • In your android/app/src/main/AndroidManifest.xml file, add a new intent filter to the activity that handles deep links for your app (for react-native this is usually the MainActivity), and specify the host and the scheme:

      <intent-filter>
          <action android:name="android.intent.action.VIEW"/>
          <category android:name="android.intent.category.DEFAULT"/>
          <category android:name="android.intent.category.BROWSABLE"/>
          <data android:host="example.page.link" android:scheme="http"/>
          <data android:host="example.page.link" android:scheme="https"/>
      </intent-filter>
  • If you wish to receive the intent in an existing instance of MainActivity, you may set the launchMode of MainActivity to singleTask in AndroidManifest.xml. See activity documentation for more information.

      <activity
        android:name=".MainActivity"
        android:launchMode="singleTask">
  • iOS

    • Add the pod

      Add the following to your Podfile:

      pod 'Firebase/DynamicLinks', '~> {{ ios.firebase.links }}'

      Run pod update.

    • Configure XCode

      1. In your Firebase console, open the Dynamic Links section.

        1. Accept the terms of service if you are prompted to do so.

        2. Take note of your project's Dynamic Links domain, which is displayed at the top of the Dynamic Links page. You need your project's Dynamic Links domain to programmatically create Dynamic Links. A Dynamic Links domain looks like app_code.page.link

          console

      2. Ensure that your app's App Store ID and your Apple Developer Team ID is specified in your app's settings. To view and edit your app's settings, go to your Firebase project's Settings page and select your iOS app. You can confirm that your Firebase project is properly configured to use Dynamic Links in your iOS app by opening the following URL:

          https://example.page.link/apple-app-site-association
        

        If your app is connected, the apple-app-site-association file contains a reference to your app's App Store ID and bundle ID. For example:

          {"applinks":{"apps":[],"details":[{"appID":"1234567890.com.example.ios","paths":["/*"]}]}}
      3. In the Info tab of your app's XCode project, create a new URL type to be used for Dynamic Links. Set the Identifier field to a unique value and the URL scheme field to either your bundle identifier or a unique value.

      4. In the Capabilities tab of your app's Xcode project, enable Associated Domains and add the following to the Associated Domains list: applinks:app_code.page.link where app_code is your dynamic links domain application code as in step 1.2 above.

      5. Update your AppDelegate.m file:

        1. Import RN Firebase Links header file:

          #import "RNFirebaseLinks.h"
        2. Add the following to the didFinishLaunchingWithOptions method before [FIRApp Configure]:

          [FIROptions defaultOptions].deepLinkURLScheme = CUSTOM_URL_SCHEME;

          ^-- where CUSTOM_URL_SCHEME is the custom URL scheme you defined in your Xcode project.

        3. Add the following inside the @implementation AppDelegate annotation:

          - (BOOL)application:(UIApplication *)application
                      openURL:(NSURL *)url
                      options:(NSDictionary<NSString *, id> *)options {
              return [[RNFirebaseLinks instance] application:application openURL:url options:options];
          }
          
          - (BOOL)application:(UIApplication *)application
          continueUserActivity:(NSUserActivity *)userActivity
          restorationHandler:(void (^)(NSArray *))restorationHandler {
              return [[RNFirebaseLinks instance] application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
          }

        You might run into situation when you need to handle more than one link configuration i.e. when using react native linking for deeplinks if that is the case you can perform check below

        - (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url
        options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
        
            BOOL handled = [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
        
            if (!handled) {
                handled = [[RNFirebaseLinks instance] application:application openURL:url options:options];
            }
        
            return handled;
        }
        
        - (BOOL)application:(UIApplication *)application
        continueUserActivity:(NSUserActivity *)userActivity
        restorationHandler:(void (^)(NSArray *))restorationHandler {
        
            BOOL handled = [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
        
            if (!handled) {
            handled = [[RNFirebaseLinks instance] application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
            }
        
            return handled;
        }

1.16 Maps

  • Install yarn add react-native-maps -E

  • Android

    • If you've defined project-wide properties (recommended) in your root build.gradle, this library will detect the presence of the following properties:

          buildscript {...}
          allprojects {...}
      
          /**
          + Project-wide Gradle configuration properties
          */
          ext {
              compileSdkVersion   = xxx
              targetSdkVersion    = xxx
              buildToolsVersion   = "xxx"
              minSdkVersion       = xxx
              supportLibVersion   = "xxx"
              playServicesVersion = "xxx" // or set latest version
              androidMapsUtilsVersion = "xxx"
          }

      or do

            buildscript {
                ext {
                    buildToolsVersion = "xxx"
                    minSdkVersion = xxx
                    compileSdkVersion = xxx
                    targetSdkVersion = xxx
                    supportLibVersion = "xxx"
                    playServicesVersion = "xxx" // or set latest version
                    androidMapsUtilsVersion = "xxx"
                }
            }
    • If you do not have project-wide properties defined and have a different play-services version than the one included in this library, use the following instead (switch 10.0.1 for the desired version):

          ...
          dependencies {
            ...
            implementation(project(':react-native-maps')){
                exclude group: 'com.google.android.gms', module: 'play-services-base'
                exclude group: 'com.google.android.gms', module: 'play-services-maps'
            }
            implementation 'com.google.android.gms:play-services-base:10.0.1'
            implementation 'com.google.android.gms:play-services-maps:10.0.1'
          }
    • (React Native all versions) Specify your Google Maps API Key:

      Add your API key to your manifest file (android/app/src/main/AndroidManifest.xml):

            <application>
              <!-- You will only need to add this meta-data tag, but make sure it's a child of application -->
              <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="Your Google maps API Key Here"/>
            </application>
  • iOS

    • If you want to enable Google Maps on iOS, obtain the Google API key and edit your AppDelegate.m as follows:

          + #import <GoogleMaps/GoogleMaps.h>
      
          @implementation AppDelegate
          ...
      
          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
          {
          +  [GMSServices provideAPIKey:@"_YOUR_API_KEY_"]; // add this line using the api key obtained from Google Console
          ...
          ```
      
          The `[GMSServices provideAPIKey]` should be the **first call** of the method.
      
    • Add the following to your Podfile above the use_native_modules! function and run pod install in the ios folder:

        # React Native Maps dependencies
        rn_maps_path = '../node_modules/react-native-maps'
        pod 'react-native-google-maps', :path => rn_maps_path
        pod 'GoogleMaps'
        pod 'Google-Maps-iOS-Utils'

1.17 React Native Paper

  • Setup

    • To get smaller bundle size by excluding modules you don't use, you can use our optional babel plugin. The plugin automatically rewrites the import statements so that only the modules you use are imported instead of the whole library. Add react-native-paper/babel to the plugins section in your babel.config.js for production environment. It should look like this:

      module.exports = {
        presets: ['module:metro-react-native-babel-preset'],
        env: {
          production: {
            plugins: ['react-native-paper/babel'],
          },
        },
      };
    • The PaperProvider component provides the theme to all the components in the framework. It also acts as a portal to components which need to be rendered at the top level.

      If you have another provider (such as Redux), wrap it outside PaperProvider so that the context is available to components rendered inside a Modal from the library:

      import * as React from 'react';
      import {Provider as PaperProvider} from 'react-native-paper';
      import {Provider as StoreProvider} from 'react-redux';
      import App from './src/App';
      import store from './store';
      
      export default function Main() {
        return (
          <StoreProvider store={store}>
            <PaperProvider>
              <App />
            </PaperProvider>
          </StoreProvider>
        );
      }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment