invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.6k stars 2.19k forks source link

🔥 [🐛] Ads not sized properly (ads' content extend beyond the parent container) #4364

Closed jeremyhalin closed 3 years ago

jeremyhalin commented 3 years ago

Issue

I'm having a lot of trouble to adjust ads' content size. I used multiple sizes but without luck. I have a view that is 100% width and 60 pixels height. I want the best ad to be displayed in this format. How to achieve that? Currently, ads are extending beyond container's dimensions like so:

Screenshot_20201007-154850

Here is my component :

import React, { useContext } from 'react';
import { SafeAreaView, StyleSheet, View } from 'react-native';
import { Layout } from '@ui-kitten/components';
import { useFocusEffect } from '@react-navigation/native';
import { BannerAd, BannerAdSize, TestIds } from '@react-native-firebase/admob';
import Config from 'react-native-config';
import MoviesPostersRepo from '../repositories/MoviesPostersRepository';
import ThemedScrollView from '../components/ThemedScrollView';
import PosterCard from '../components/PosterCard';
import ExplanationsModal from '../components/ExplanationsModal';
import HeaderRightWrapper from '../components/HeaderRightWrapper';
import HeaderRightPrevNext from '../components/HeaderRightPrevNext';
import StickyHeader from '../components/StickyHeader';
import LoadingView from '../components/LoadingView';
import UserContext from '../contexts/UserContext';

const adUnitId = __DEV__ ? TestIds.BANNER : Config.LEVEL_BANNER_AD_ID;

export default ({ route, navigation }) => {
  const { number } = route.params;

  const { user } = useContext(UserContext);

  const [levels, setLevels] = React.useState([]);
  const [helpModalVisible, setHelpModalVisible] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [levelsDone, setLevelsDone] = React.useState(0);
  const [loading, setLoading] = React.useState(true);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      title: 'Films (images)',
    });
  }, [navigation]);

  useFocusEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <HeaderRightWrapper>
          <HeaderRightPrevNext
            isPrevDisabled={number <= 1}
            isNextDisabled={!MoviesPostersRepo.isPackUnlocked(number + 1)}
            packNumber={number}
            navigation={navigation}
            onPressPrev={() => {
              navigation.navigate('MoviesPostersPack', {
                number: number - 1,
              });
            }}
            onPressNext={() => {
              navigation.navigate('MoviesPostersPack', {
                number: number + 1,
              });
            }}
          />
        </HeaderRightWrapper>
      ),
    });
  }, [navigation, number]);

  // Do something when the screen is focused
  useFocusEffect(
    React.useCallback(() => {
      const allLevels = MoviesPostersRepo.getPackLevels(number);
      const levelsFound = MoviesPostersRepo.getCountLevelsFoundForPack(number);

      setLevels(allLevels);
      setProgress((levelsFound / allLevels.length) * 100);
      setLevelsDone(levelsFound);

      setLoading(false);
      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [number]),
  );

  if (loading) {
    return <LoadingView />;
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <ThemedScrollView stickyHeaderIndices={[0]}>
        <StickyHeader
          progress={progress}
          progressText={`${levelsDone} sur ${levels.length}`}
          title={`Pack ${number}`}
        />
        <Layout style={styles.container}>
          {levels &&
            levels.map((level, index) => (
              <PosterCard
                key={index}
                index={index}
                movieDbId={level.movieDbId}
                movieDbType="movie"
                found={level.found}
                movieTitle={level.movieTitle}
                onCardPress={() => {
                  navigation.navigate('MoviePosterLevel', {
                    levelId: level.id,
                  });
                }}
              />
            ))}
        </Layout>
      </ThemedScrollView>
      {!user.removeAds && (
        <View
          style={{
            height: 60,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <BannerAd
            unitId={adUnitId}
            size={BannerAdSize.FULL_BANNER}
            requestOptions={{
              requestNonPersonalizedAdsOnly: true,
              keywords: ['films', 'séries', 'cinéma'],
            }}
          />
        </View>
      )}
      <ExplanationsModal
        visible={helpModalVisible}
        onBackdropPress={() => setHelpModalVisible(false)}
        onPress={() => setHelpModalVisible(false)}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 8,
    flexDirection: 'row',
    justifyContent: 'center',
    flexWrap: 'wrap',
  },
  safeArea: {
    flex: 1,
  },
});

Project Files

Javascript

Click To Expand

#### `package.json`: ```json{ "name": "app", "version": "1.0.0", "private": true, "scripts": { "android": "react-native run-android", "build-android": "cd android && gradlew bundleRelease", "test-release": "react-native run-android --variant=release", "gradle-clean": "cd android && gradlew clean", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint . --ext .js,.jsx --fix", "lint-fix": "eslint . --ext .js,.jsx --fix", "format": "prettier --write ./src" }, "dependencies": { "@eva-design/eva": "2.0.0", "@react-native-community/async-storage": "^1.12.0", "@react-native-community/masked-view": "^0.1.10", "@react-native-firebase/admob": "^7.6.5", "@react-native-firebase/app": "^8.4.3", "@react-navigation/native": "^5.7.3", "@react-navigation/stack": "^5.9.0", "@ui-kitten/components": "5.0.0", "@ui-kitten/eva-icons": "5.0.0", "@ui-kitten/metro-config": "^5.0.0", "js-levenshtein": "^1.1.6", "lottie-react-native": "^3.5.0", "react": "16.11.0", "react-native": "0.62.2", "react-native-config": "^1.3.3", "react-native-device-info": "^5.6.5", "react-native-gesture-handler": "^1.7.0", "react-native-google-play-game-services": "github:jeremyhalin/react-native-google-play-game-services", "react-native-iap": "^4.5.3", "react-native-onesignal": "^3.9.1", "react-native-reanimated": "^1.13.0", "react-native-safe-area-context": "^3.1.7", "react-native-screens": "^2.10.1", "react-native-share": "^3.8.3", "react-native-splash-screen": "^3.2.0", "react-native-svg": "^12.1.0", "react-native-swipe-gestures": "^1.0.5", "realm": "^6.1.0" }, "devDependencies": { "@babel/core": "^7.11.6", "@babel/runtime": "^7.11.2", "babel-eslint": "^10.1.0", "babel-jest": "^24.9.0", "babel-plugin-transform-remove-console": "^6.9.4", "eslint": "^7.10.0", "eslint-config-airbnb": "^18.2.0", "eslint-config-prettier": "^6.12.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jsx-a11y": "^6.3.1", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-react": "^7.21.3", "eslint-plugin-react-native": "^3.10.0", "metro-react-native-babel-preset": "^0.58.0", "prettier": "^2.1.2", "react-native-svg-transformer": "^0.14.3", "react-test-renderer": "16.11.0" }, "jest": { "preset": "react-native", "transformIgnorePatterns": [] } } ``` #### `firebase.json` for react-native-firebase v6: ```json { "react-native": { "admob_android_app_id": "ca-app-pub-********", "admob_ios_app_id": "" } } ```

iOS

Click To Expand

#### `ios/Podfile`: - [x] I'm not using Pods - [ ] I'm using Pods and my Podfile looks like: ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 29 supportLibVersion = "28.0.0" } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:3.5.2") classpath 'com.google.gms:google-services:4.3.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() maven { url 'https://maven.google.com' } maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() maven { url 'https://www.jitpack.io' } } ext { gms_library_version = '17.0.0' } } ``` #### `android/app/build.gradle`: ```groovy buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal } dependencies { classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]' } } apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin' apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' project.ext.envConfigFiles = [ debug: ".env.development", release: ".env.production", ] apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ enableHermes: false, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false); android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.memorablequotes" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 34 versionName "2.0.3" multiDexEnabled true } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } release { if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) { storeFile file(MYAPP_UPLOAD_STORE_FILE) storePassword MYAPP_UPLOAD_STORE_PASSWORD keyAlias MYAPP_UPLOAD_KEY_ALIAS keyPassword MYAPP_UPLOAD_KEY_PASSWORD } } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://facebook.github.io/react-native/docs/signed-apk-android. signingConfig signingConfigs.release minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } packagingOptions { pickFirst "lib/armeabi-v7a/libc++_shared.so" pickFirst "lib/arm64-v8a/libc++_shared.so" pickFirst "lib/x86/libc++_shared.so" pickFirst "lib/x86_64/libc++_shared.so" } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { implementation 'com.android.support:multidex:1.0.3' implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" implementation "com.google.android.gms:play-services-games:${gms_library_version}" implementation "com.google.android.gms:play-services-auth:${gms_library_version}" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } if (enableHermes) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' } apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'App' include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') include ':react-native-onesignal' project(':react-native-onesignal').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-onesignal/android') include ':react-native-config' project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android') include ':react-native-device-info' project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android') include ':lottie-react-native' project(':lottie-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/lottie-react-native/src/android') include ':react-native-splash-screen' project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android') include ':react-native-iap' project(':react-native-iap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-iap/android') apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java package com.myapp; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage; import com.lugg.ReactNativeConfig.ReactNativeConfigPackage; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.airbnb.android.react.lottie.LottiePackage; import org.devio.rn.splashscreen.SplashScreenReactPackage; import com.dooboolab.RNIap.RNIapPackage; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class aClass = Class.forName("com.myapp.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: Windows 10 10.0.19041 CPU: (16) x64 AMD Ryzen 7 2700X Eight-Core Processor Memory: 8.19 GB / 15.95 GB Binaries: Node: 14.8.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.14.7 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: API Levels: 23, 28, 29, 30 Build Tools: 28.0.3, 29.0.2, 30.0.0 System Images: android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom Android NDK: Not Found Windows SDK: AllowAllTrustedApps: Disabled IDEs: Android Studio: Version 4.0.0.0 AI-193.6911.18.40.6626763 Visual Studio: 16.4.29905.134 (Visual Studio Community�2019) Languages: Java: Not Found Python: Not Found npmPackages: @react-native-community/cli: Not Found react: 16.11.0 => 16.11.0 react-native: 0.62.2 => 0.62.2 react-native-windows: Not Found npmGlobalPackages: *react-native*: Not Found ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [ ] **iOS** but have not tested behavior on Android - [x] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `8.4.3` - **`Firebase` module(s) you're using that has the issue:** - `admob:7.6.5` - **Are you using `TypeScript`?** - `N` & `VERSION`


mikehardy commented 3 years ago

Similar to your other issue, without a fully executable App.js it's unlikely anyone can reproduce this and help, with the additional note unfortunately there is not a lot of community help troubleshooting AdMob problems so my best advice is to cook up an App.js that shows this (and any other AdMob problems you are having) in isolation so there's at least a chance others can reproduce, but I would proceed without waiting into node_modules to see if you can trace paths and find out where assumptions are violated and giving you unwanted results

jeremyhalin commented 3 years ago

I found what causes the banner to overflow its parent container. It's alignItems: 'center'. But another problem appeared, ads are not centered horizontally when not full width. ❓ Regarding the second screenshot, how can we make the Ad to align horizontally?

Here is an App.js you can easily try:

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

const adUnitId = __DEV__ ? TestIds.BANNER : 'your-admob-ad-id';

export default () => {
  return (
    <View>
      <Text style={{ color: 'white' }}>
        Below is an Ad in a parent View with alignItems: 'center'
      </Text>
      <View style={{ alignItems: 'center' }}>
        <BannerAd
          unitId={adUnitId}
          size={BannerAdSize.FULL_BANNER}
          requestOptions={{
            requestNonPersonalizedAdsOnly: true,
            keywords: ['films', 'séries', 'cinéma'],
          }}
        />
      </View>
      <Text style={{ color: 'white' }}>
        Below is an Ad in root View without direct parent container
      </Text>
      <BannerAd
        unitId={adUnitId}
        size={BannerAdSize.FULL_BANNER}
        requestOptions={{
          requestNonPersonalizedAdsOnly: true,
          keywords: ['films', 'séries', 'cinéma'],
        }}
      />
    </View>
  );
};

Here are some screenshots showing the results: Screenshot_20201009-115658 Screenshot_20201009-115525

RodolfoGS commented 3 years ago

You could try adding width to parent view. Example:

import { Dimensions } from 'react-native';
....

<View style={{ alignItems: 'center', width: Dimensions.get('window').width }}>
  <BannerAd
    unitId={adUnitId}
    size={BannerAdSize.FULL_BANNER}
    requestOptions={{
      requestNonPersonalizedAdsOnly: true,
      keywords: ['films', 'séries', 'cinéma'],
    }}
  />
</View>
jeremyhalin commented 3 years ago

@RodolfoGS is this the best practice? How to make <BannerAd> component taking full width space and center horizontally when ad is not 100% width?

stale[bot] commented 3 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

jeremyhalin commented 3 years ago

No update on this topic? I feel like it shouldn't be the default behavior that ads content overflow its parent container.

mikehardy commented 3 years ago

All work in open source is actually in the open, if there's no update there is no work happening, which does allow you to make certain assumptions though: any work you do here to improve the module will not be duplicated, and we welcome PRs - I personally work with contributors to make sure they are in good shape for merge and I produce releases regularly in order to make sure everyone's work is generally available

stale[bot] commented 3 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

sabinayakc commented 1 year ago

@jeremyhalin @RodolfoGS Have you tried using BannerAdSize.INLINE_ADAPTIVE_BANNER OR BannerAdSize.ANCHORED_ADAPTIVE_BANNER along with alignItems: 'center' in your parent view ?

That kinda worked for me.