やること
- ReactNativeでGoogleAdmobの広告を入れる
- 広告は画面の下部にバナー広告を挿入する
ライブラリインストール
npmでreact-native-google-mobile-ads
をインストールする
npm install react-native-google-mobile-ads
Google Admobにてアプリを作成する
- GoogleAdmobにアクセス
- 「アプリを追加」を押下
- 「新しいアプリの設定」画面で、プラットフォーム(Android・iOS)・アプリはサポートされているアプリストアに登録されていますか?を選択する
- アプリ名を入力し、「アプリを追加」ボタンを押下する
- 「追加しました」が表示されたら、「完了」ボタンを押下する
- 「広告ユニットを追加」ボタンを押下する
- 「バナー」を選択する
- 広告ユニット名を適当に入力し、「パートナーでの入札」はチェックせずに、「広告ユニットの作成」ボタンを押下
- 「広告ユニットを作成しました」が表示されるので、アプリIDと広告ユニットIDをひかえておく。
バナー広告用のコンポーネントの作成
MyAdmob.tsx
import {Platform, View} from 'react-native'; import mobileAds, { BannerAd, BannerAdSize, TestIds, } from 'react-native-google-mobile-ads'; type Props = { size: BannerAdSize; }; const MyAdmob: React.FC<Props> = props => { const isDebug = false; // テスト時はtrueにする mobileAds() .setRequestConfiguration({ // Indicates that you want your content treated as child-directed for purposes of COPPA. tagForChildDirectedTreatment: true, }) .then(() => { // Request config successfully set! console.log('Request config successfully set!'); }); // 実際に広告配信する際のID // 広告ユニット(バナー)を作成した際に表示されたものを設定する const adUnitID = Platform.select({ ios: 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy', android: 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy', }); const getUnitId = () => { return isDebug ? TestIds.BANNER : adUnitID ?? TestIds.BANNER; }; return <BannerAd {...props} unitId={getUnitId()} />; }; export default MyAdmob;
App.tsxに広告のコンポーネントの表示を組み込む
return ( <> ・・・ <MyAdmob size={BannerAdSize.ANCHORED_ADAPTIVE_BANNER} /> </> );
アプリケーションIDをapp.jsonに設定する
- app.json に以下を設定する
{ "name": "", "displayName": "", "react-native-google-mobile-ads": { "android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx", "ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx" } }
シミュレーターを実行して確認
はい、表示されています!
リリース版のときは、MyAdmobコンポーネントのisDebug=falseにするのを忘れずに・・・