メインコンテンツへスキップ

実装方法

バナー広告は2つの方法で実装できます。
方式説明推奨
Data AttributesHTML属性のみで簡単に実装迅速な実装
renderAd広告読み込みタイミングを直接制御細かい制御が必要な場合
開発環境ではテストユニットIDを使用してください:PUBLIC_TEST_UNIT_ID_320_100

1. Data Attributes方式

最も簡単な方式で、data-adrop-unit属性を追加するだけでSDKが自動的に広告を読み込みます。
function BannerAd() {
  return (
    <div
      data-adrop-unit="YOUR_UNIT_ID"
      data-adrop-context-id="YOUR_CONTEXT_ID"
      data-adrop-theme="light"
      data-adrop-custom-click="true"  // カスタムクリック処理の有効化
    />
  );
}

Data Attributes

data-adrop-unit
string
必須
Ad Controlコンソールで作成したユニットID
data-adrop-context-id
string
data-adrop-theme
string
デフォルト:"light"
テーマ設定(lightまたはdark) - ダークモード設定を参照
data-adrop-custom-click
boolean
デフォルト:false
カスタムクリック処理の有効化 - trueに設定するとSDKが自動で目的地URLに移動せず、adClickedイベントのみ発生させます。開発者がクリック動作を直接実装できます。

広告の再リクエスト

Reactのkeyを変更してコンポーネントを再マウントすると、広告が再リクエストされます。
function App() {
  const [adKey, setAdKey] = useState(0);

  const reloadAd = () => {
    setAdKey(prev => prev + 1);
  };

  return (
    <>
      <div key={adKey} data-adrop-unit="YOUR_UNIT_ID" />
      <button onClick={reloadAd}>広告を更新</button>
    </>
  );
}

2. renderAd方式

広告読み込みタイミングを直接制御したい場合に使用します。
import { useEffect, useRef } from 'react';
import Adrop from '@adrop/ads-web-sdk';

function BannerAd() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adrop = Adrop.instance();

    if (containerRef.current) {
      adrop.renderAd(containerRef.current, {
        unit: 'YOUR_UNIT_ID',
        contextId: 'YOUR_CONTEXT_ID',
        theme: 'light',
        useCustomClick: true  // カスタムクリック処理の有効化
      });
    }

  }, []);

  return <div ref={containerRef} />;
}

renderAdオプション

unit
string
必須
Ad Controlコンソールで作成したユニットID
uid
string
ユーザー識別子(SDK設定値を個別の広告枠で上書きする場合に使用)
contextId
string
theme
string
デフォルト:"light"
テーマ設定(lightまたはdark) - ダークモード設定を参照
useCustomClick
boolean
デフォルト:false
カスタムクリック処理の有効化 - trueに設定するとSDKが自動で目的地URLに移動せず、adClickedイベントのみ発生させます。開発者がクリック動作を直接実装できます。

広告の再リクエスト

renderAd()を再度呼び出すと、広告が再リクエストされます。Data Attributesで作成した広告枠にも使用できます。
function BannerAd() {
  const containerRef = useRef<HTMLDivElement>(null);

  const reloadAd = () => {
    const adrop = Adrop.instance();
    if (containerRef.current) {
      adrop.renderAd(containerRef.current, {
        unit: 'YOUR_UNIT_ID'
      });
    }
  };

  return (
    <>
      <div ref={containerRef} />
      <button onClick={reloadAd}>広告を更新</button>
    </>
  );
}
Data Attributesで作成した広告枠にrenderAd()を呼び出す場合、data attributesに存在しない項目や修正したい項目のみを渡せば十分です。

広告の削除

clear()を呼び出してコンテナから広告を削除できます。
const adrop = Adrop.instance();
adrop.clear(containerRef.current);

広告サイズ

コンテナをユニットに登録したサイズに合わせて設定してください。
<div
  data-adrop-unit="YOUR_UNIT_ID"
  style={{ width: 320, height: 100 }}
/>
区分サイズ設定配置
ダイレクト広告レスポンシブ対応、高さ必須水平/垂直中央
バックフィル広告初期幅合わせ、高さ必須水平中央

イベント処理

広告の状態変化を検出して、適切なUI処理ができます。
import { useEffect, useRef } from 'react';
import Adrop from '@adrop/ads-web-sdk';

function BannerAd({ unitId }: { unitId: string }) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adrop = Adrop.instance();

    // 広告受信成功
    const handleReceived = (unit: string, adData: any) => {
      console.log('広告受信:', unit);
    };

    // 配信可能なダイレクト広告なし
    const handleNoFill = (unit: string) => {
      console.warn('広告なし:', unit);
    };

    // リクエスト失敗
    const handleFailed = (unit: string) => {
      console.error('広告失敗:', unit);
    };

    // インプレッション
    const handleImpression = (unit: string) => {
      console.log('広告表示:', unit);
    };

    // クリック
    const handleClicked = (unit: string) => {
      console.log('広告クリック:', unit);
    };

    // バックフィル広告なし
    const handleBackfillNoFill = (unit: string) => {
      console.warn('バックフィル広告なし:', unit);
    };

    // 特定ユニットのみフィルタリング
    const filter = { unit: unitId };

    adrop.on(Adrop.Events.AD_RECEIVED, handleReceived, filter);
    adrop.on(Adrop.Events.AD_NO_FILL, handleNoFill, filter);
    adrop.on(Adrop.Events.AD_FAILED, handleFailed, filter);
    adrop.on(Adrop.Events.AD_IMPRESSION, handleImpression, filter);
    adrop.on(Adrop.Events.AD_CLICKED, handleClicked, filter);
    adrop.on(Adrop.Events.AD_BACKFILL_NO_FILL, handleBackfillNoFill, filter);

    if (containerRef.current) {
      adrop.renderAd(containerRef.current, { unit: unitId });
    }

    return () => {
      adrop.off(Adrop.Events.AD_RECEIVED, handleReceived);
      adrop.off(Adrop.Events.AD_NO_FILL, handleNoFill);
      adrop.off(Adrop.Events.AD_FAILED, handleFailed);
      adrop.off(Adrop.Events.AD_IMPRESSION, handleImpression);
      adrop.off(Adrop.Events.AD_CLICKED, handleClicked);
      adrop.off(Adrop.Events.AD_BACKFILL_NO_FILL, handleBackfillNoFill);

    };
  }, [unitId]);

  return <div ref={containerRef} />;
}

サポートするイベント

イベント定数説明
広告受信AD_RECEIVED広告リクエスト成功
広告なしAD_NO_FILL配信可能なダイレクト広告なし
リクエスト失敗AD_FAILED広告リクエスト失敗
インプレッションAD_IMPRESSION広告インプレッション記録
クリックAD_CLICKEDユーザーが広告をクリック
バックフィルなしAD_BACKFILL_NO_FILLバックフィル広告なし
コンポーネントのアンマウント時に必ずoff()でイベントリスナーを解除してください。

AdData

イベントハンドラーで受け取る広告データです。詳細なフィールド情報はリファレンス > AdDataを参照してください。

カスタムクリック処理

useCustomClickが有効化されると、SDKが自動で目的地URLに移動しなくなります。代わりにクリックイベントを処理してカスタム動作を実装できます。
import { useEffect, useRef } from 'react';
import Adrop from '@adrop/ads-web-sdk';

function CustomClickBannerAd({ unitId }: { unitId: string }) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adrop = Adrop.instance();
    const filter = { unit: unitId };

    // カスタム動作で広告クリック処理
    const handleClicked = (unit: string, adData: any) => {
      console.log('広告クリック:', unit);
      console.log('目的地URL:', adData.destinationURL);
      
      // カスタムクリック動作実装
      // 例: 確認ダイアログ表示、分析トラッキングなど
      const userConfirmed = confirm('広告主ページを訪問しますか?');
      if (userConfirmed && adData.destinationURL) {
        window.open(adData.destinationURL, '_blank');
      }
    };

    adrop.on(Adrop.Events.AD_CLICKED, handleClicked, filter);

    if (containerRef.current) {
      adrop.renderAd(containerRef.current, {
        unit: unitId,
        useCustomClick: true
      });
    }

    return () => {
      adrop.off(Adrop.Events.AD_CLICKED, handleClicked);
    };
  }, [unitId]);

  return <div ref={containerRef} />;
}
カスタムクリック処理が有効化されると、ユーザーが広告をクリックしたときの動作を完全に制御できます。destinationURLadClickedイベントデータに含まれて提供されます。

完全なサンプル

BannerAd.tsx

import { useEffect, useRef } from 'react';
import Adrop from '@adrop/ads-web-sdk';

interface BannerAdProps {
  unitId: string;
  contextId?: string;
  theme?: 'light' | 'dark';
  onReceived?: (adData: any) => void;
  onFailed?: () => void;
  onClicked?: () => void;
}

function BannerAd({
  unitId,
  contextId,
  theme = 'light',
  onReceived,
  onFailed,
  onClicked
}: BannerAdProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adrop = Adrop.instance();
    const filter = { unit: unitId };

    const handleReceived = (_: string, adData: any) => onReceived?.(adData);
    const handleFailed = () => onFailed?.();
    const handleClicked = () => onClicked?.();

    adrop.on(Adrop.Events.AD_RECEIVED, handleReceived, filter);
    adrop.on(Adrop.Events.AD_FAILED, handleFailed, filter);
    adrop.on(Adrop.Events.AD_CLICKED, handleClicked, filter);

    if (containerRef.current) {
      adrop.renderAd(containerRef.current, {
        unit: unitId,
        contextId,
        theme
      });
    }

    return () => {
      adrop.off(Adrop.Events.AD_RECEIVED, handleReceived);
      adrop.off(Adrop.Events.AD_FAILED, handleFailed);
      adrop.off(Adrop.Events.AD_CLICKED, handleClicked);

    };
  }, [unitId, contextId, theme]);

  return <div ref={containerRef} className="banner-ad-container" />;
}

export default BannerAd;

使用例

import BannerAd from './components/BannerAd';

function App() {
  return (
    <div>
      <header>
        <BannerAd
          unitId="HEADER_BANNER_UNIT_ID"
          onClicked={() => console.log('ヘッダーバナークリック')}
        />
      </header>

      <main>
        <h1>コンテンツ</h1>
      </main>

      <footer>
        <BannerAd
          unitId="FOOTER_BANNER_UNIT_ID"
          theme="dark"
        />
      </footer>
    </div>
  );
}

バックフィル広告

バックフィル広告が有効な場合、直接広告がないときに自動的にバックフィル広告がリクエストされます。adData.formatで広告タイプを区別できます。
import { useEffect, useRef } from 'react';
import Adrop from '@adrop/ads-web-sdk';

function BannerAd({ unitId }: { unitId: string }) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const adrop = Adrop.instance();
    const filter = { unit: unitId };

    // 広告受信(直接広告またはバックフィル)
    const handleReceived = (unit: string, adData: any) => {
      if (adData.format === 'backfill') {
        console.log('バックフィル広告がロードされました');
      } else {
        console.log('直接広告がロードされました');
      }
    };

    // 直接広告なし(バックフィルリクエスト開始)
    const handleNoFill = (unit: string) => {
      console.log('直接広告なし、バックフィル広告をリクエスト中...');
    };

    // バックフィル広告もなし
    const handleBackfillNoFill = (unit: string) => {
      console.warn('バックフィル広告もありません');
      // 広告エリアを非表示にするなどの処理
    };

    adrop.on(Adrop.Events.AD_RECEIVED, handleReceived, filter);
    adrop.on(Adrop.Events.AD_NO_FILL, handleNoFill, filter);
    adrop.on(Adrop.Events.AD_BACKFILL_NO_FILL, handleBackfillNoFill, filter);

    if (containerRef.current) {
      adrop.renderAd(containerRef.current, { unit: unitId });
    }

    return () => {
      adrop.off(Adrop.Events.AD_RECEIVED, handleReceived);
      adrop.off(Adrop.Events.AD_NO_FILL, handleNoFill);
      adrop.off(Adrop.Events.AD_BACKFILL_NO_FILL, handleBackfillNoFill);
    };
  }, [unitId]);

  return <div ref={containerRef} />;
}
開発環境テスト: アプリに連携された広告ユニットのうち少なくとも1つが収益化中であれば、localhostからでもバックフィル広告のリクエストが可能です。承認されていないドメインでは AD_BACKFILL_NO_FILL イベントが発生します。