Implement AdMob in React Native with Firebase
This post is done on a special request from one of our thousands readers. If you have more requests, let me know in the comments
In this post, you will learn how to implement AdMob functionality, i.e. Google advertisements, in React Native apps. We will implement this in a simple React Native app and test on iOS simulator.
As we all know, advertisements are the major source of income for all tech giants like Google, Facebook, Twitter etc. Google ads are one of the most popular ads out there, and the mobile version of Google ads is what they call AdMob.
Type of AdMob ads
Banner: A basic ad format that appears at the top & bottom of the device screen.
Interstitial: Full-page ads appear at natural breaks & transitions, such as level completion. Supports video content.
Rewarded: Full page Ads reward users for watching short videos and interacting with playable ads and surveys. Good for monetizing free-to-play users. Supports video content.
Native: Customizable ad format that matches the look & feel of your app. Ads appear inline with app content. Supports video content. For now, Native ads are only possible in Native apps, not in hybrid apps like the ones based on Ionic or React Native.
Let us look at the underlying frameworks for this post. If you are conversant with React Native and Firebase, skip these sections and go to the code segment of the post.
What is React-Native
Before we move into the blog, let’s first clarify what framework we are using. We are using React Native, which is one among many hybrid app frameworks available. The closest rivals of React Native are Flutter and Ionic.
TLDR; — React Native (RN) apps are more “native” than web-view apps made by Cordova / Ionic. React Native crates actual Java and Swift codes for apps, unlike the web-view apps which essentially run in a … web-view.
React Native is a JavaScript framework for writing natively rendering mobile applications. It’ is based on React, Facebook’s JavaScript library for building user interfaces, but instead of targeting the browser, it targets mobile platforms. Because most of the code you write can be shared between platforms, React Native makes it easy to simultaneously develop for both Android and iOS.
React Native applications render using real mobile UI components, not web-views, and will look and feel like any other native mobile application. React Native also exposes JavaScript interfaces for platform APIs, so your React Native apps can access platform features like the phone camera, or the user’s location. Facebook, Palantir, TaskRabbit etc are already using it in production for user-facing applications.
What is Firebase
If you don’t know much about Firebase … you need to catch up with latest tech news. Firebase is the popular stuff in the market today. One can use Firebase to create quick mobile app back-ends, with a ton of built-in and ready-to-integrate features.
Some of the quick integrations available with Firebase are
- Email Authentication
- Social logins
- Real-time database
- Analytics
- Crashlytics
- Push notifications
- In-app messages
- Remote config
and much more. Firebase is quickly growing to become the most popular mobile app back-end platform.
So, why use AdMob with Firebase ?
Umm, well it’s not really necessary to use Firebase for AdMob. You can integrate AdMob in your app independent of Firebase. I am using Firebase connected AdMob for two reasons
- I have been using Invertase React Native Firebase plugin for quite some time. They have great documentations and so, I have trust in their products. Their AdMob dependency, in-turn, depends on React-Native Firebase. Hence.
- With Firebase and AdMob connected, you can view great insights about your AdMob campaign. This video explains better
As an alternative, you can use other React-Native AdMob dependencies for showing ads in your React Native app. I will probably cover one of those in my blogs later.
Enough of story-telling, let’s dive into — how to implement AdMob in React Native apps
Post structure
We will go in a step-by-step manner to explore the AdMob feature implementation. This is my break-down of the blog
STEPS
- Create a Firebase project and get required information
- Create a simple React Native app
- Setup your AdMob account
- Setup AdMob dependency
- Implement different types of Ads in your RN App
- Build the app on iOS device and test
So let’s dive right in!
Step 1 — Create Firebase project
For Admob implementation, all we need from Firebase project is — GoogleService-Info.plist
file (for iOS) or google-services.json
file for Android
Follow these steps
- Login into Firebase Console
- Create Firebase Project
- Add an iOS app (or an Android app), register the Bundle ID, and give your app a name
- Download
GoogleService-Info.plist
. We’ll need this file later in the project
Follow this video for the above steps if you need
Step 2 — Create basic React Native app
First, make sure you have all pre-requisites to create a react-native app as per the official documentation.
At the time of this post, I have React-Native version 0.62 & node 12.14.0
Create a blank react-native app
$ react-native init AdMob
This will create a basic React-native app which you can run in a device or simulator. (either Android or iOS)
We’ll create a simple page with few buttons that will trigger Ads. While banner ad generally doesn’t need a trigger, interstitial ads and reward ads need a trigger. These triggers are generally completion of a level in a game app etc. My basic UI for the ad page looks like this
Step 3— Setup your Admob account
- Signup then Sign in to your AdMob account at https://apps.admob.com.
- Click Apps in the sidebar.
- Click Add app to add a new app or click View all apps to search a list of all of the apps you’ve added to AdMob.
- In the App Settings options, you can see your App ID. This is the ID you will need to connect your app to Google AdMob in your React Native app.
- In the Ad Units section, you can add multiple types of Ad units. For more details on adding Ad Units, check out the following detailed step-by-step instructions for
AdMob has a ton of other settings for how, when and where your ads should show up, but all that for later. In this post, we’ll limit the discussion to “How to display basic ad units in a React Native app”
Step 4 — Install AdMob dependency and implement
For this post, as I explained earlier, we are using AdMob with Firebase. The dependency we are using for this is React-Native Firebase. This main dependency contains several service modules, AdMob is one of them.
4.1 Install React-Native Firebase for iOS
In your existing React Native app, add the main dependency using
$ yarn add @react-native-firebase/app
# For iOS
cd ios && pod install
4.2 Import Firebase config file in Xcode
Next, open the project (/ios/{projectName}.xcworkspace
) in Xcode editor. Add your GoogleService-Info.plist
file to the project by right clicking on the project name and “Add files” to the project, as demonstrated below. Ensure the ‘Copy items if needed’ checkbox is enabled.
4.3 Initialize Firebase in Xcode
Open the AppDelegate file within your project /ios/{projectName}/AppDelegate.m
. At the top of the file import the Firebase module:
#import <Firebase.h>
Within the didFinishLaunchingWithOptions
method, add the configure
method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
....
Rebuild your project by running commands
$ cd ios/
$ pod install --repo-update
4.4 Install AdMob dependency
Install the module using
$ yarn add @react-native-firebase/admob
# For iOS
cd ios/ && pod install
Once completed, re-run your project in iOS device using
$ react-native run-ios
or run using Xcode.
The above steps often lead to some small mistake. If the app doesn’t start up fine, check these
- Clean your project and build again
- Make sure you have latest CocoaPods version
- Make sure your PodFile mentions the dependency as
pod ‘RNFBAdMob’, :path => ‘../node_modules/@react-native-firebase/admob’
4.5 Adding your AdMob App ID
The AdMob module needs to be hooked up to your own Google AdMob account using the App ID we noted down in Step 3
Add the ID to your root level firebase.json
file (create one) under the react-native
object like following
{ "react-native": { "admob_android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx", "admob_ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx"
} }
Rebuild your application for the changes to take effect.
Step 5 — Implement different types of Ads in the app
Once everything is setup, let us implement different types of Ads in the app.
Banner Ad
Banner ads are implemented as a <BannerAd>
tag itself. You can place it in your React Native app just like any other tag. Make sure you import the dependency
import { TestIds, BannerAd, BannerAdSize} from '@react-native-firebase/admob';
I imported the Banner ad at the bottom of the page, in a View
positioned absolute
as follows
<BannerAd unitId={TestIds.BANNER} size={BannerAdSize.SMART_BANNER} requestOptions={{ requestNonPersonalizedAdsOnly: true,}} onAdLoaded={() => { console.log('Advert loaded');}} onAdFailedToLoad={(error) => { console.error('Advert failed to load: ', error);}} />
Here, I have used a test ID TestIds.BANNER
. This uses a default test ID provided by AdMob. You will replace this with your production Ad unit ID when you release the app
DO NOT use the test ID in your production app, and DO NOT use your production Ad Unit ID while developing the app
The resulting ad looks like this
Interstitial Ad
Interstitial Ads work on a trigger. Because these are full page ads, they are not always visible as Banner Ads.
To implement interstitial ads, import the required dependency and follow the code below
Again, TestIds.INTERSTITIAL
is a test ID. Replace it with production Ad ID when releasing the app.
.load()
method loads the ad. This ad takes some time in loading. That is why .show()
is called on the LOADED
event. If you call the .show()
method immediately after .load()
the app with crash.
Finally .show()
shows the ad on full screen, like following
Reward Ad
Again, reward Ads are similar to interstitial ads in the trigger mechanism. To implement, import the required dependency and follow the code below
Again, TestIds.REWARDED
is a test ID. Replace it with production Ad ID when releasing the app.
.load()
method loads the ad. This ad takes some time in loading. That is why .show()
is called on the LOADED
event. If you call the .show()
method immediately after .load()
the app with crash.
Reward Ads also have a .EARNED_REWARD
event, which is called when the reward ad throws a callback (generally when user has seen the required length of the ad). After this callback, you can provide user with the reward.
Finally .show()
shows the ad on full screen. The reward ad will look like this
Step 6: Testing the app on a device
To run the iOS app, you should specify simulator
$ react-native run-ios --simulator=”iPhone X”
To run Android app, you should start emulator first (or connect a device), either via Android Studio or adb
, then call
$ react-native run-android
Tada ! You have learnt how to implement AdMob ads in your React Native app. 🎉
Conclusion
In this blog, we learned how to implement Google AdMob functionality in React Native app. AdMob functionality is a must for an app where user wants to earn some revenue from ad clicks. This comes in handy when your app has a large number of users, and you do not charge users for anything in the app. So ads become your direct revenue source. You can also combine the interstitial ads and rewards ads with in-app rewards like a level up in a game, extra lives etc.
Complete source code of this tutorial is available in the react-native-admob