2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactアプリにバナー広告を表示させてみた

Last updated at Posted at 2023-02-18

モバイル向けB2C Webサービスの収益を強固なものにするため、メイン画面にバナー広告を挿入しました。
本記事で解説するのは Google AdSense ではなく、自前の広告マイクロサービスと連携する方式です。
バナー広告は数分単位で動的に切り替わります。

マイクロサービスと連携する部分は割愛し、僕がデモンストレーション用にローカル環境で作成したコードを掲載します。

myapp/src/footer/index.js
import React, {useState, useEffect} from 'react';
import foo from '../assets/img/foo.png';
import bar from '../assets/img/bar.png';
import baz from '../assets/img/baz.png';

export default function Footer() {
	// 広告データをハードコーディング
	const ads = [
		[ 'スポンサー企業様その1', foo, 'https://foo.example.com/' ],
		[ 'スポンサー企業様その2', bar, 'https://bar.example.com/' ],
		[ 'スポンサー企業様その3', bar, 'https://baz.example.com/' ],
	];

	const [count, setCount] = useState(0);

	useEffect(() => {  // マウント時にのみ実行
		const time = setInterval(() => {
			setCount(prevCount => (prevCount + 1) % ads.length);
		}, 3000);
		return () => clearInterval(time);
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<div className="footer-content">
			<img key={ads[count][2]}
				alt={ads[count][0]}
				src={ads[count][1]}  // バナー広告の画像イメージ
				onClick={() => window.open(ads[count][2], "_blank")}  // 企業URL
			/>
		</div>
	);
}

npm start したところ、3秒単位でバナー広告が切り替わり、クリックすると企業サイトに飛びました。
useStateuseEffectなど React Hooks の使い方は、こちらの記事を参考にしました。

さて、ここで終わりとしても良いのですが、見た目を少し凝ってみたくなりました。

myapp/src/assets/scss/home.scss
#footer-myapp {
	height: 60px;
	width: 100%;
	display: block;
	box-sizing: border-box;
	margin-left: auto;
	margin-right: auto;
	padding: 0 50px;

	.footer-content {
		height: 100%;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		img {
			cursor: pointer;
			height: 100%;
			animation: rendered 1s ease;
			animation-iteration-count: 1;
			@keyframes rendered {
				0% {
					opacity: 0;
				}
				100% {
					opacity: 1;
				}
			}
		}
	}
}
@media (min-width: 600px) {
	.MuiToolbar-gutters {
		padding-left: 43px;
		padding-right: 43px;
	}
}

透明度を指定するopacityと、動きに変化を付けるanimationを組み合わせ、ふんわりゆっくりバナーを切り替えるようにしてみました。如何でしょうか。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?