UNPKG

react-native-google-mobile-ads

Version:

React Native Google Mobile Ads is an easy way to monetize mobile apps with targeted, in-app advertising.

511 lines (382 loc) 23.2 kB
# Displaying Ads The Google Mobile Ads package allows you to display five types of adverts; App Open, Interstitial, Rewarded, Rewarded Interstitial, and Banner. ## App Open Ads App open ads are a special ad format intended for publishers wishing to monetize their app load screens. App open ads can be closed by your users at any time. App open ads can be shown when users bring your app to the foreground. App open ads are shown when your application launches or when users bring your application to the foreground. To make sure you have an ad ready to display when a user opens your app, you'll want to have a reference to an ad ready to use. That means you must preload an app open ad before you need to show the ad. That way, your app open ad is ready to show the next time the app is opened. To create a new app open ad, call the `createForAdRequest` method from the `AppOpenAd` class. 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: ```js import { AppOpenAd, TestIds, AdEventType } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.APP_OPEN : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const appOpenAd = AppOpenAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); // Preload an app open ad appOpenAd.load(); // Show the app open ad when user brings the app to the foreground. appOpenAd.show(); ``` ### Consider ad expiration Key Point: Ad references in the app open beta will time out after four hours. Ads rendered more than four hours after request time will no longer be valid and may not earn revenue. This time limit is being carefully considered and may change in future beta versions of the app open format. ### Cold starts and loading screens The above documentation assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory. An example of a cold start is when a user opens your app for the first time. With cold starts, you won't have a previously loaded app open ad that's ready to be shown right away. The delay between when you request an ad and receive an ad back can create a situation where users are able to briefly use your app before being surprised by an out of context ad. This should be avoided because it is a bad user experience. The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, do not show the ad. ### Best practices Google built app open ads to help you monetize your app's loading screen, but it's important to keep best practices in mind so that your users enjoy using your app. Make sure to: - Wait to show your first app open ad until after your users have used your app a few times. - Show app open ads during times when your users would otherwise be waiting for your app to load. - If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen after receiving the `onAdClosed` event. ## Interstitial Ads Interstitials are full-screen ads that cover the interface of an app until closed by the user. These types 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` class. 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: ```js import { InterstitialAd, TestIds, AdEventType } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const interstitial = InterstitialAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); ``` The second argument is additional optional request options object to be sent whilst loading an advert, such as keywords & location. Setting additional request options helps AdMob choose better tailored ads from the network. View the [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) source code to see the full range of options available. The call to `createForAdRequest` returns an instance of the [`InterstitialAd`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/ads/InterstitialAd.ts) class, which provides a number of utilities for loading and displaying interstitials. To listen to events, such as when the advert from the network has loaded or when an error occurs, we can subscribe via the `addAdEventListener` method: ```jsx import React, { useEffect, useState } from 'react'; import { Button, Platform, StatusBar } from 'react-native'; import { InterstitialAd, AdEventType, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const interstitial = InterstitialAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); function App() { const [loaded, setLoaded] = useState(false); useEffect(() => { const unsubscribeLoaded = interstitial.addAdEventListener(AdEventType.LOADED, () => { setLoaded(true); }); const unsubscribeOpened = interstitial.addAdEventListener(AdEventType.OPENED, () => { if (Platform.OS === 'ios') { // Prevent the close button from being unreachable by hiding the status bar on iOS StatusBar.setHidden(true); } }); const unsubscribeClosed = interstitial.addAdEventListener(AdEventType.CLOSED, () => { if (Platform.OS === 'ios') { StatusBar.setHidden(false); } }); // Start loading the interstitial straight away interstitial.load(); // Unsubscribe from events on unmount return () => { unsubscribeLoaded(); unsubscribeOpened(); unsubscribeClosed(); }; }, []); // No advert ready to show yet if (!loaded) { return null; } return ( <Button title="Show Interstitial" onPress={() => { interstitial.show(); }} /> ); } ``` The code above subscribes to the interstitial events (via `addAdEventListener()`) and immediately starts to load a new advert from the network (via `load()`). Once an advert is available, local state is set, re-rendering the component showing a `Button`. When pressed, the `show` method on the interstitial instance is called and the advert is shown over-the-top of your application. You can subscribe to other various events with `addAdEventListener` listener such as if the user clicks the advert, or closes the advert and returns back to your app. To see the full list of available events, view the [`AdEventType`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/AdEventType.ts) source code. If needed, you can reuse the existing instance of the `InterstitialAd` class to load more adverts and show them when required. ## 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 rewarded ad, call the `createForAdRequest` method from the `RewardedAd` class. 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: ```js import { RewardedAd, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.REWARDED : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const rewarded = RewardedAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); ``` The second argument is additional optional request options object to be sent whilst loading an advert, such as keywords & location. Setting additional request options helps AdMob choose better tailored ads from the network. View the [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) source code to see the full range of options available. The call to `createForAdRequest` returns an instance of the [`RewardedAd`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/ads/RewardedAd.ts) class, which provides a number of utilities for loading and displaying rewarded ads. To listen to events, such as when the advert from the network has loaded or when an error occurs, we can subscribe via the `addAdEventListener` method: ```js import React, { useEffect, useState } from 'react'; import { Button } from 'react-native'; import { RewardedAd, RewardedAdEventType, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.REWARDED : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const rewarded = RewardedAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); function App() { const [loaded, setLoaded] = useState(false); useEffect(() => { const unsubscribeLoaded = rewarded.addAdEventListener(RewardedAdEventType.LOADED, () => { setLoaded(true); }); const unsubscribeEarned = rewarded.addAdEventListener( RewardedAdEventType.EARNED_REWARD, reward => { console.log('User earned reward of ', reward); }, ); // Start loading the rewarded ad straight away rewarded.load(); // Unsubscribe from events on unmount return () => { unsubscribeLoaded(); unsubscribeEarned(); }; }, []); // No advert ready to show yet if (!loaded) { return null; } return ( <Button title="Show Rewarded Ad" onPress={() => { rewarded.show(); }} /> ); } ``` The code above subscribes to the rewarded ad events (via `addAdEventListener()`) and immediately starts to load a new advert from the network (via `load()`). Once an advert is available, local state is set, re-rendering the component showing a `Button`. When pressed, the `show` method on the rewarded ad instance is called and the advert is shown over-the-top of your application. Like Interstitial Ads, you can listen to the events with the `addAdEventListener` such as when the user clicks the advert or closes the advert and returns back to your app. However, you can listen to an extra `EARNED_REWARD` event which is triggered when user completes the advert action. An additional `reward` payload is sent with the event, containing the amount and type of rewarded (specified via the dashboard). To learn more, view the [`RewardedAdEventType`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/RewardedAdEventType.ts) source code. If needed, you can reuse the existing instance of the `RewardedAd` class to load more adverts and show them when required. While the `EARNED_REWARD` event only occurs on the client, Server Side Verification (or SSV) can be used for confirming a user completed an advert action. For this, you have to specify the Server Side Verification callback URL in your Ads dashboard. You can customize SSV parameters when your SSV callback is called by setting the `serverSideVerificationOptions` field in your [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) parameter. ```js const rewardedAd = RewardedAd.createForAdRequest(adUnitId, { serverSideVerificationOptions: { userId: '9999', customData: 'my-custom-data', }, }); ``` If you request an Advert as in the example above, AdMob will call your server with the `userId` and `customData` fields as shown below: ``` [14/Aug/2020 12:51:43] "GET /views/admob-ssv/?ad_network=...&ad_unit=...&custom_data=my-custom-data&reward_amount=1&reward_item=test_reward_item&timestamp=1597377102267&transaction_id=148cc85...&user_id=9999&signature=MEUCIQCQSi3cQ2PlxlEAkpN...&key_id=3335... HTTP/1.1" 200 0 ``` You still need to verify these incoming requests yourself to ensure they are genuine. To learn more about callback parameters and verifying, see the [AdMob SDK Server Side Verification(SSV) documentation](https://developers.google.com/admob/android/rewarded-video-ssv). ## Rewarded Interstitial Ads Rewarded Interstitial Ads are full-screen ads that cover the interface of an app until closed by the user. The content of a rewarded interstitial advert is controlled via the Google AdMob dashboard. The purpose of a rewarded interstitial 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). Unlike rewarded ads, users aren't required to opt-in to view a rewarded interstitial. To create a new rewarded interstitial ad, call the `createForAdRequest` method from the `RewardedInterstitialAd` class. 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: ```js import { RewardedInterstitialAd, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.REWARDED_INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const rewardedInterstitial = RewardedInterstitialAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); ``` The second argument is additional optional request options object to be sent whilst loading an advert, such as keywords & location. Setting additional request options helps AdMob choose better tailored ads from the network. View the [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) source code to see the full range of options available. The call to `createForAdRequest` returns an instance of the [`RewardedInterstitialAd`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/ads/RewardedInterstitialAd.ts) class, which provides a number of utilities for loading and displaying rewarded interstitial ads. To listen to events, such as when the advert from the network has loaded or when an error occurs, we can subscribe via the `addAdEventListener` method: ```js import React, { useEffect, useState } from 'react'; import { Button } from 'react-native'; import { RewardedInterstitialAd, RewardedAdEventType, TestIds, } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.REWARDED_INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; const rewardedInterstitial = RewardedInterstitialAd.createForAdRequest(adUnitId, { keywords: ['fashion', 'clothing'], }); function App() { const [loaded, setLoaded] = useState(false); useEffect(() => { const unsubscribeLoaded = rewardedInterstitial.addAdEventListener( RewardedAdEventType.LOADED, () => { setLoaded(true); }, ); const unsubscribeEarned = rewardedInterstitial.addAdEventListener( RewardedAdEventType.EARNED_REWARD, reward => { console.log('User earned reward of ', reward); }, ); // Start loading the rewarded interstitial ad straight away rewardedInterstitial.load(); // Unsubscribe from events on unmount return () => { unsubscribeLoaded(); unsubscribeEarned(); }; }, []); // No advert ready to show yet if (!loaded) { return null; } return ( <Button title="Show Rewarded Interstitial Ad" onPress={() => { rewardedInterstitial.show(); }} /> ); } ``` The code above subscribes to the rewarded interstitial ad events (via `addAdEventListener()`) and immediately starts to load a new advert from the network (via `load()`). Once an advert is available, local state is set, re-rendering the component showing a `Button`. When pressed, the `show` method on the rewarded interstitial ad instance is called and the advert is shown over-the-top of your application. Like Interstitial Ads, you can listen to the events with the `addAdEventListener` such as when the user clicks the advert or closes the advert and returns back to your app. However, you can listen to an extra `EARNED_REWARD` event which is triggered when user completes the advert action. An additional `reward` payload is sent with the event, containing the amount and type of rewarded (specified via the dashboard). To learn more, view the [`RewardedAdEventType`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/RewardedAdEventType.ts) source code. If needed, you can reuse the existing instance of the `RewardedInterstitialAd` class to load more adverts and show them when required. While the `EARNED_REWARD` event only occurs on the client, Server Side Verification (or SSV) can be used for confirming a user completed an advert action. For this, you have to specify the Server Side Verification callback URL in your Ads dashboard. You can customize SSV parameters when your SSV callback is called by setting the `serverSideVerificationOptions` field in your [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) parameter. ```js const rewardedInterstitialAd = RewardedInterstitialAd.createForAdRequest(adUnitId, { serverSideVerificationOptions: { userId: '9999', customData: 'my-custom-data', }, }); ``` If you request an Advert as in the example above, AdMob will call your server with the `userId` and `customData` fields as shown below: ``` [14/Aug/2020 12:51:43] "GET /views/admob-ssv/?ad_network=...&ad_unit=...&custom_data=my-custom-data&reward_amount=1&reward_item=test_reward_item&timestamp=1597377102267&transaction_id=148cc85...&user_id=9999&signature=MEUCIQCQSi3cQ2PlxlEAkpN...&key_id=3335... HTTP/1.1" 200 0 ``` You still need to verify these incoming requests yourself to ensure they are genuine. To learn more about callback parameters and verifying, see the [AdMob SDK Server Side Verification(SSV) documentation](https://developers.google.com/admob/android/rewarded-video-ssv). ## Banner Ads (component) 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`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/ads/BannerAd.tsx) component. The `unitId` and `size` props are required to display a banner: ```js import React, { useState, useRef } from 'react'; import { Platform } from 'react-native'; import { BannerAd, BannerAdSize, TestIds, useForeground } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.ADAPTIVE_BANNER : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; function App() { const bannerRef = useRef < BannerAd > null; // (iOS) WKWebView can terminate if app is in a "suspended state", resulting in an empty banner when app returns to foreground. // Therefore it's advised to "manually" request a new ad when the app is foregrounded (https://groups.google.com/g/google-admob-ads-sdk/c/rwBpqOUr8m8). useForeground(() => { Platform.OS === 'ios' && bannerRef.current?.load(); }); return ( <BannerAd ref={bannerRef} unitId={adUnitId} size={BannerAdSize.ANCHORED_ADAPTIVE_BANNER} /> ); } ``` The `size` prop takes a [`BannerAdSize`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/BannerAdSize.ts) type, and once the advert is available, will fill the space for the chosen size. <Info> If no inventory for the size specified is available, an error will be thrown via `onAdFailedToLoad`! </Info> The `requestOptions` prop is additional optional request options object to be sent whilst loading an advert, such as keywords & location. Setting additional request options helps AdMob choose better tailored ads from the network. View the [`RequestOptions`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/types/RequestOptions.ts) documentation to view the full range of options available. The component also exposes props for listening to events, which you can use to handle the state of your app is the user or network triggers an event: - `onAdClosed` - `onAdFailedToLoad` - `onAdLeftApplication` - `onAdOpened` - `onPaid` &mdash; On [impression-level ad revenue](https://support.google.com/admob/answer/11322405?hl=en) events. Each render of the component loads a single advert, allowing you to display multiple adverts at once. If you need to reload/change an advert for a currently mounted component, you'll need to force a re-render inside of your own code. ### Collapsible banner ads Collapsible banner ads are banner ads that are initially presented as a larger overlay, with a button to collapse them to the originally requested banner size. Collapsible banner ads are intended to improve performance of anchored ads that are otherwise a smaller size. This guide shows how to turn on collapsible banner ads for existing banner placements. ```js import React from 'react'; import { BannerAd, BannerAdSize, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.ADAPTIVE_BANNER : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; function App() { return ( <BannerAd unitId={adUnitId} size={BannerAdSize.ANCHORED_ADAPTIVE_BANNER} requestOptions={{ networkExtras: { collapsible: 'bottom', }, }} /> ); } ``` ### Displaying Google Ad Manager Banner You can also display a Google Ad Manager banner ad unit. In this case, you have to import `GAMBannerAd` component and use `sizes` prop instead of `size` prop: ```js import React from 'react'; import { GAMBannerAd, BannerAdSize, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.GAM_BANNER : '/xxx/yyyy'; function App() { return <GAMBannerAd unitId={adUnitId} sizes={[BannerAdSize.FULL_BANNER]} />; } ``` The `sizes` prop takes an array of [`BannerAdSize`](https://github.com/invertase/react-native-google-mobile-ads/blob/main/src/BannerAdSize.ts) types. ## Native Ads Head over to the [Native Ads](/native-ads) documentation.