React Native Google Mobile Ads

repository·main·Indexed 21 days ago

https://github.com/invertase/react-native-google-mobile-ads

A React Native wrapper for the Google Mobile Ads SDK (version 16.4.0) that enables AdMob monetization for iOS and Android apps. It provides full TypeScript support and supports multiple ad formats, including App open, Banner (anchored adaptive, inline adaptive, collapsible, and fixed size), Native, Interstitial, Rewarded, and Rewarded Interstitial ads. The library is compatible with both the Old Architecture and the React Native New Architecture.

Tokens
27.9K
Snippets
85
Records
119
Agent score
73%

What's inside react-native-google-mobile-ads

  1. Overview of React Native Google Mobile Ads

    main
    React Native Google Mobile Ads is a React Native wrapper around the native Google-Mobile-Ads SDKs for both iOS and Android. It allows developers to monetize their applications using AdMob. The library is designed with three core principles: extensive testing (>95% coverage), first-class TypeScript support, and comprehensive documentation.
  2. Supported Ad Formats in react-native-google-mobile-ads

    main

    The react-native-google-mobile-ads module provides integration for six different types of advertisements. Once you have completed the initial setup, you can implement the following formats:

    • App Open Ads: Ads that appear when a user opens or switches back to the app.
    • Interstitial Ads: Full-screen ads that cover the interface of the app.
    • Rewarded Ads: Ads that reward users with in-app benefits after watching.
    • Banner Ads: Small display ads that occupy a portion of the screen.
    • Rewarded Interstitial Ads: A hybrid format that combines the full-screen nature of interstitials with the reward mechanism of rewarded ads.
    • Native Ads: Ads that can be customized to match the look and feel of your app's UI.
  3. Supported Ad formats

    main

    The module supports six distinct types of advertisements:

    1. App Open Ads: Full-screen ads shown when an app is opened or brought to the foreground.
    2. Banner Ads: Component-based ads displayed within the UI layout.
    3. Native Ads: Component-based ads that can be styled to match the app's native look and feel.
    4. Interstitial Ads: Full-screen ads that interrupt the user flow (e.g., between levels in a game).
    5. Rewarded Ads: Full-screen ads that provide users with an in-app reward after watching.
    6. Rewarded Interstitial Ads: A hybrid format that combines the properties of interstitial and rewarded ads.
  4. Understand Ad serving modes based on consent

    main

    Google ads are categorized into several modes depending on user consent:

    • Personalized ads
    • Non-personalized ads
    • Limited ads
    • Technical ads

    It is critical to understand how these modes affect ad delivery. The AdsConsent helper provides the tools to request consent, but the developer is responsible for ensuring the resulting consent status is correctly handled and reflected throughout the application logic.

  5. Supported Ad Formats

    main

    The library supports several Google AdMob ad formats:

    • App open: Ads intended for app load screens.
    • Banner: Rectangular ads that can be anchored (top/bottom) or inline with content. Supported types include:
      • Anchored adaptive: Full-width, auto-height, and always on-screen.
      • Inline adaptive: Larger, taller banners intended for scrolling content.
      • Collapsible: Improved performance for anchored ads.
      • Fixed size (legacy): Specific dimensions like Banner (320x50), Large banner (320x100), Medium rectangle (300x250), full banner (468x60), and leaderboard (728x90).
    • Native: Customizable ads that match the app's design and layout.
    • Interstitial: Full-page ads placed at natural app transitions.
    • Rewarded: Incentivized ads where users watch videos, playables, or surveys to earn in-app items.
    • Rewarded Interstitial: Incentivized ads that appear automatically during natural transitions without requiring explicit user opt-in.
  6. Use Ad Inspector for real-time ad analysis

    main

    Ad Inspector is an in-app overlay for authorized devices that allows real-time analysis of test ad requests. It is used to:

    • Inspect ad units
    • Verify if ads are filling as expected
    • Identify and resolve errors
    • View Open Bidding and mediation details per request
    • Test individual third-party Open Bidding or waterfall mediation ad sources
    • Verify configuration for Open Bidding and waterfall mediation
  7. Handle App Open Ad expiration and cold starts

    main

    When implementing App Open Ads, keep these constraints in mind:

    • Ad Expiration: Ad references in the app open beta will time out after four hours. Ads rendered more than four hours after the request time may be invalid and won't earn revenue.
    • Cold Starts: On a cold start (when the app is launched but not previously in memory), you won't have a preloaded ad ready. To avoid a bad user experience where an ad appears unexpectedly after the user has already started interacting with the app, use a loading screen to load app assets and only show the ad from that loading screen. If the app finishes loading and reaches main content before the ad is ready, do not show the ad.
  8. Implement full-screen ad flow with hooks

    main

    To display an ad, you typically follow this lifecycle:

    1. Initialize: Call the hook with an Ad Unit ID.
    2. Load: Call the load() function (often inside a useEffect) to fetch the ad from the network.
    3. Show: When a user triggers an action, check isLoaded. If true, call show(). If false, proceed with your fallback logic (e.g., navigating to the next screen).
    4. Handle Closure: Listen to the isClosed state to perform actions after the user dismisses the ad.
    import { useInterstitialAd, TestIds } from 'react-native-google-mobile-ads';
    
    export default function App({ navigation }) {
      const { isLoaded, isClosed, load, show } = useInterstitialAd(TestIds.INTERSTITIAL);
    
      useEffect(() => {
        // Start loading the interstitial straight away
        load();
      }, [load]);
    
      useEffect(() => {
        if (isClosed) {
          // Action after the ad is closed
          navigation.navigate('NextScreen');
        }
      }, [isClosed, navigation]);
    
      return (
        <View>
          <Button
            title="Navigate to next screen"
            onPress={() => {
              if (isLoaded) {
                show();
              } else {
                // No advert ready to show yet
                navigation.navigate('NextScreen');
              }
            }}
          />
        </View>
      );
    }
  9. Migrate AdsConsent to the User Messaging Platform (UMP) SDK

    main

    In version 5 and later, react-native-google-mobile-ads transitioned from the old Consent SDK to Google's User Messaging Platform (UMP) SDK. This change aligns with IAB standards and Apple's App Tracking Transparency (ATT) requirements.

    Key Changes in the AdsConsent API:

    • requestInfoUpdate(): Now accepts an optional AdsConsentInfoOptions object instead of a list of publisherIds. It returns a new AdsConsentInfo interface.
    • showForm(): No longer accepts parameters. It returns an AdsConsentFormResult interface containing the new AdsConsentStatus.
    • Removed Methods: getAdProviders, getStatus, and setStatus have been removed.
    • Removed Testing/Debug Methods: addTestDevices, setDebugGeography, and setTagForUnderAgeOfConsent are removed. Their functionality is now handled via the AdsConsentInfoOptions object passed to requestInfoUpdate().
    • New Method: getUserChoices() can be used to inspect specific consent choices made by the user.

    Unlike the old SDK, the new AdsConsentStatus primarily indicates whether you should show the consent modal to a user, rather than providing detailed user preference information directly through the status enum.

  10. Install react-native-google-mobile-ads

    main

    Install the module based on your project type:

    React Native (Bare):

    npm install react-native-google-mobile-ads

    Expo:

    npx expo install react-native-google-mobile-ads

    Note for Android: Before releasing, you must select "Yes, my app contains ads" in the Google Play Console under "Policy and programmes" > "App content" > "Manage".

    npm install react-native-google-mobile-ads
    # or
    npx expo install react-native-google-mobile-ads
  11. Configure Server Side Verification (SSV) for Rewarded Ads

    main

    While the EARNED_REWARD event is triggered on the client, you can use Server Side Verification (SSV) to confirm rewards on your backend. This prevents client-side tampering.

    To use SSV:

    1. Configure your SSV callback URL in the Google AdMob dashboard.
    2. When creating the ad request, pass userId and customData via the serverSideVerificationOptions field in the RequestOptions object.
    3. AdMob will call your server with these parameters, along with reward details (amount, item, etc.) and a signature for verification.

    Note: You must verify the incoming requests on your server to ensure they are genuine.

    const rewardedAd = RewardedAd.createForAdRequest(adUnitId, {
      serverSideVerificationOptions: {
        userId: '9999',
        customData: 'my-custom-data',
      },
    });