Earn Money using AdMob Integration in React Native App

AdMob Integration in React Native App

This is our seventh post of React Native Firebase series. Firebase module provides an easy way to integrate AdMobs in React Native. In this example we will see what is AdMob? and how to integrate AdMob in React Native App? How to see your earning and how to get that in your bank account?

Firebase AdMob

The AdMob module allows you to display adverts to your users. All adverts are served over the Google AdMob network, meaning a Google AdMob account is required.

Firebase AdMob Ads

The module supports three types of Ads:

  1. Full screen Interstitial Ads
  2. Full screen Rewarded Ads
  3. Component based Banner Ads

1. Interstitials Ads

Interstitials are full-screen ads that cover the interface of an app until closed by the user. These type of ads are programmatically loaded and then shown at a suitable point during your application flow (e.g. after a level on a gaming app has been completed, or game over). The ads can be preloaded in the background to ensure they’re ready to go when needed.

To create a new interstitial, call the createForAdRequest method from the InterstitialAd. The first argument of the method is the “Ad Unit ID“. For testing, we can use a Test ID, however for production the ID from the Google AdMob dashboard under “Ad units” should be used

import {
  InterstitialAd,
  TestIds,
  AdEventType
} from '@react-native-firebase/admob';

const adUnitId = 
    __DEV__ ? TestIds.INTERSTITIAL :
    'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';

const interstitial = InterstitialAd.createForAdRequest(
  adUnitId,
  {
    requestNonPersonalizedAdsOnly: true,
    keywords: ['fashion', 'clothing'],
  }
);

To listen to events, such as when the advert from the network has loaded or when an error occurs, we can subscribe via the onAdEvent method and immediately starts to load a new advert from the network (via load()).

useEffect(() => {
  const eventListener = interstitial.onAdEvent(type => {
    if (type === AdEventType.LOADED) {
      setLoaded(true);
    }
  });

  // Start loading the interstitial straight away
  interstitial.load();

  // Unsubscribe from events on unmount
  return () => {
    eventListener();
  };
}, []);

To show the Ad you can call show method anytime, it will call interstitial instance and the advert is shown over-the-top of your application.

interstitial.show();

2. Rewarded Ads

Rewarded Ads are full-screen ads that cover the interface of an app until closed by the user. The content of a rewarded advert is controlled via the Google AdMob dashboard.

The purpose of a rewarded ad is to reward users with something after completing an action inside of the advert, such as watching a video or submitting an option via an interactive form. If the user completes the action, you can reward them with something (e.g. in-game currency).

To create a new interstitial, call the createForAdRequest method from the RewardedAd. The first argument of the method is the “Ad Unit ID“. For testing, we can use a Test ID, however for production the ID from the Google AdMob dashboard under “Ad units” should be used

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

const adUnitId =
    __DEV__ ? TestIds.INTERSTITIAL :
    'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';

const rewarded = RewardedAd.createForAdRequest(
  adUnitId,
  {
    requestNonPersonalizedAdsOnly: true,
    keywords: ['fashion', 'clothing'],
  }
);

To listen to events, such as when the advert from the network has loaded or when an error occurs, we can subscribe via the onAdEvent method

useEffect(() => {
  const eventListener = rewarded.onAdEvent((type, error, reward) => {
    if (type === RewardedAdEventType.LOADED) {
      setLoaded(true);
    }

    if (type === RewardedAdEventType.EARNED_REWARD) {
      console.log('User earned reward of ', reward);
    }
  });

  // Start loading the rewarded ad straight away
  rewarded.load();

  // Unsubscribe from events on unmount
  return () => {
    eventListener();
  };
}, []);

To show the Ad you can call show method anytime, it will call interstitial instance and the advert is shown over-the-top of your application.

rewarded.show();

Like Interstitial Ads, the events returns from the onAdEvent listener trigger when the user clicks the advert or closes the advert and returns back to your app.

However, an extra EARNED_REWARD event can be triggered if the user completes the advert action. An additional reward property is sent with the event, containing the amount and type of rewarded (specified via the dashboard). An additional reward property is sent with the event, containing the amount and type of rewarded (specified via the dashboard).

3. Banner Ads

Banner ads are partial adverts which can be integrated within your existing application. Unlike Interstitial and Rewarded Ads, a Banner only takes up a limited area of the application and displays an advert within the area. This allows you to integrate adverts without a disruptive action.

The module exposes a BannerAd component. The unitId and size props are required to display a banner:

import React from 'react';
import {
  BannerAd,
  BannerAdSize,
  TestIds
} from '@react-native-firebase/admob';

const adUnitId =
    __DEV__ ? TestIds.BANNER :
    'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';

function App() {
  return (
    <BannerAd
      unitId={adUnitId}
      size={BannerAdSize.FULL_BANNER}
      requestOptions={{
        requestNonPersonalizedAdsOnly: true,
      }}
    />
  );
}

The size prop takes a BannerAdSize type, and once the advert is available, will fill the space for the chosen size.

Example Description

In this example we will integrate AdMob with our app and will see how to use it. On a single screen we will show Banner Ad and 2 button to show interstitial and rewarded Ads.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Integration of Firebase SDK

For starting with any of the React Native Firebase Example you will need to integrate Firebase in your app, I have specially made a separate post in detail for this where you will see point to point process to add Firebase in your React Native App for Android and iOS both.

Please visit How to Integrate Firebase in Android and iOS App and come back for the next step.

Once you are done with the Firebase integration you can install the further dependencies.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project using

cd ProjectName

For the React Native Firebase we need to install and setup the app module

npm install @react-native-firebase/app --save

Now install the admob module

npm install @react-native-firebase/admob --save

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but for iOS we need to install the pods. So to install the pods use

cd ios/ && pod install --repo-update && cd ..

Setup for AdMob

Before we start with the code you need to setup some things. First you will need a Google AdMob account which you can create easily. Once you create the account you will land on the Apps tab where you can see all of your apps. You can add N number of apps in the same account which will help you to monitor your earnings in a single place. Once you are on Apps tab click on “ADD YOUR FIRST APP” to add our app.

react_native_admob_setup1

You will be asked to choose the platform, if your app will work on both the platform then you have to do the same for two times.

react_native_admob_setup2

Once you select your platform you need to give the name of your app. This will be identifier for you, it is not necessary to match the name with something.

react_native_admob_setup3

Once you add your app you can see App ID in App settings section, this is the identifier for Google AdMob to identify your app.

react_native_admob_setup4

Once you see the same just copy it and create a firebase.json file in the root of your React Native project,  and add the admob_android_app_id & admob_ios_app_id keys with the IDs from the Google AdMob console. If you have only one then you can remove the other once or both will be acceptable.

// /firebase.json
{
  "react-native": {
    "admob_android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx",
    "admob_ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx"
  }
}

Once you add this firebase.json please rebuild your app.

Now you have to create some Ad units, Ad units are basically the type of ad you want to show, creating this Ad unit will help you to understand the source of earning. This will give you the clear picture about the user engagement. To create the Ad unit you can see Ad units option in Apps.

react_native_admob_setup6

react_native_admob_setup7

react_native_admob_setup8

react_native_admob_setup9

Once you create the Ad units you can see some id (like ca-app-pub-xxxxxxxxxxxx/xxxxxxxxx) which is a unique identifier for the Ad.

react_native_admob_setup10

Code to Integrate AdMob in React Native

Please open App.js in any code editor and replace the code with the following code

App.js

// #7 Earn Money using AdMob Integration in React Native App
// https://aboutreact.com/react-native-admob-ads/

// Import React and Component
import React, { useEffect } from "react";
import {
  View,
  Text,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
} from "react-native";

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

import {
  InterstitialAd,
  RewardedAd,
  RewardedAdEventType,
  TestIds,
  AdEventType,
  BannerAd,
  BannerAdSize,
} 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!
  });

const interstialAdUnitId = __DEV__
  ? TestIds.INTERSTITIAL
  : "ca-app-pub-7470375419739273/1165043718";

const interstitial = InterstitialAd.createForAdRequest(
  interstialAdUnitId,
  {
    requestNonPersonalizedAdsOnly: true,
    keywords: ["fashion", "clothing"],
  }
);

const rewardedAdUnitId = __DEV__
  ? TestIds.REWARDED
  : "ca-app-pub-7470375419739273/3954858586";

const rewarded = RewardedAd.createForAdRequest(
  rewardedAdUnitId,
  {
    requestNonPersonalizedAdsOnly: true,
    keywords: ["fashion", "clothing"],
  }
);

const bannerAdUnitId = __DEV__
  ? TestIds.BANNER
  : "ca-app-pub-7470375419739273/3954858586";

const App = () => {
  useEffect(() => {
    // Event listener for interstitial Ads
    const interstitialAdEventListener = interstitial.onAdEvent(
      (type) => {
        if (type === AdEventType.LOADED) {
          console.log("Interstitial Ad Loaded");
        }
      }
    );

    // Start loading the interstitial straight away
    interstitial.load();

    // Event listener for rewarded Ads
    const rewardedAdEventListener = rewarded.onAdEvent(
      (type, error, reward) => {
        if (type === RewardedAdEventType.LOADED) {
          console.log("Rewarded Ad Loaded");
        }

        if (type === RewardedAdEventType.EARNED_REWARD) {
          console.log("User earned reward of ", reward);
        }
      }
    );

    // Start loading the rewarded ad straight away
    rewarded.load();

    // Unsubscribe from events on unmount
    return () => {
      interstitialAdEventListener();
      rewardedAdEventListener();
    };
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.heading}>
        React Native + AdMob Integration{"\n\n"}
        www.aboutreact.com
      </Text>
      <View
        style={{
          flex: 1,
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <TouchableOpacity
          style={styles.buttonStyle}
          activeOpacity={0.5}
          onPress={() => interstitial.show()}
        >
          <Text style={styles.buttonTextStyle}>
            Show Interstitial Ad
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.buttonStyle}
          activeOpacity={0.5}
          onPress={() => rewarded.show()}
        >
          <Text style={styles.buttonTextStyle}>
            Show Rewarded Ad
          </Text>
        </TouchableOpacity>
      </View>
      <BannerAd
        unitId={bannerAdUnitId}
        size={BannerAdSize.ADAPTIVE_BANNER}
        requestOptions={{
          requestNonPersonalizedAdsOnly: true,
        }}
      />
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
    padding: 16,
  },
  heading: {
    fontSize: 20,
    textAlign: "center",
    marginTop: 30,
  },
  buttonStyle: {
    minWidth: 300,
    backgroundColor: "#7DE24E",
    borderWidth: 0,
    color: "#FFFFFF",
    borderColor: "#7DE24E",
    height: 40,
    alignItems: "center",
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 20,
    marginBottom: 25,
  },
  buttonTextStyle: {
    color: "#FFFFFF",
    paddingVertical: 10,
    fontSize: 16,
  },
});

Output Screenshots

react_native_admob1   react_native_admob2   react_native_admob3

European User Consent

Out of the box, AdMob does not handle any related regulations which you may need to enforce on your application. It is up to the developer to implement and handle this on a user-by-user basis. You must consent to EEA users being served both personalized and non-personalized adverts before showing them. For more information, see Requesting Consent from European Users.

The AdMob module provides a AdConsent helper to help developers quickly implement consent flows within their application. See the European User Consent page for full examples of how to integrate the helper into your application.

On Android, you must update the “Contains ads” setting in the Google Play Store dashboard before releasing your app (under “Pricing & Distribution”).

This is how we can integrate AdMobs in our React Native App for Android and iOS and can earn money using AdMob Integration.

Once you integrate AdMob in your React Native App you can easily see your earning on AdMob dashboard and can see this post to help you to transfer the amount in your bank account.

If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

1 thought on “Earn Money using AdMob Integration in React Native App”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.