Using Ads (AdMob) in React Native with Expo
Contents
Summary (概要)
using Mac
using expo (version 45)
using React Native (version 0.68.2)
using typescript
using VScode
using node (version 16)
The expo version is 45. This is because the latest version of expo is 46 as of August 2022, but when using AdMob, the packages to be installed are different between 45 and 46, and 46 is troublesome. (expoのversionは45とします。これは、2022年8月の時点でexpoの最新versionは46ですが、AdMobを使う場合、45と46でインストールするパッケージが違って46だと面倒なので、とりあえず45で確実に開発したいためです。)
Create a new project for React Native with Expo (新規プロジェクトの作成)
Please refer to the following page because it is based on the following page. (以下のページを前提にしているので、以下のページを参照してください。) React Nativeのプロジェクトでsrcフォルダを使う場合
Use Admob (AdMobを利用する)
The best way to add ads to mobile apps is with Google's AdMob. (携帯アプリに広告を追加する場合、googleのAdMobを利用するのが一番良いです。)
install expo-ads-admob
Up to Expo sdk 45, if you want to use AdMob, install expo-ads-admob. (Expo sdk 45までの場合、AdMob を利用したい場合は、expo-ads-admobをインストールします。)
// Up to expo sdk 45 OK (expo sdk 45までの場合OK)
expo install expo-ads-admob
Create a component file dedicated to Admob
Admob専用のコンポーネントファイルを作ります。 componentsフォルダにAdmob.tsxというファイルを作成します。 ├── src │ ├── App.tsx │ └── components │ └─── Admob.tsx
AdMob.tsx code
import React from 'react';
import { Platform, View, Text } from 'react-native';
import { AdMobBanner } from 'expo-ads-admob';
class BannerAd extends React.Component {
bannerError: ((string: any) => void) | undefined;
render(){
return <>
<View>
<Text>aaa</Text>
<AdMobBanner
bannerSize="fullBanner"
adUnitID="ca-app-pub-3940256XXX942YYY/29347ZZZZ" // Test ID, Replace with your-admob-unit-id
servePersonalizedAds={true}
onDidFailToReceiveAdWithError={this.bannerError} />
</View>
</>;
}
}
export default BannerAd;
App.tsx code
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { registerRootComponent } from 'expo';
import BannerAd from './components/Admob'; // ← Add 追加
export default function App() {
return <>
<View style={styles.container}>
<BannerAd /> // ← Add 追加
<Text>Open up App.tsx to start working on your app!</Text>
<StatusBar style="auto" />
</View>
</>;
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
registerRootComponent(App);
After changing the two files App.tsx and AdMob.tsx as above, please check the display of Android simulator and iPhone simulator. (App.tsxとAdMob.tsxの2つのファイルを上記のように変更したら、Android simulatorとiPhone simulatorの表示を確認してください。) If all goes well, you should see a test ad like the image below. (上手くいけば以下の画像のようにテスト広告が表示されているはずです。)

Happily ever after.
(めでたし、めでたし。)