React DFP Documentation

  ·  Build Status Npm Downloads Minizipped size GitHub license Dependencies
Minizipped size

 Refreshable ads 2

In some scenarios, under certain conditions, your application might need to refresh ads, sometimes reacting to some user actions (for instance when the user browses a photo gallery), or sometimes, we'd like to have our app refreshing the ads at a defined time interval (forinstance, every 5 minutes).

The following example demonstrates how to accomplish refreshable ads with react dfp. In this case, we make use of the following three pieces:

- DFPSlotsProvider : we use it to configure global settings (dfp id, etc).

- AdSlot : used to define ad slots in your page.

- DFPManager.refresh(...id): after the ads have been rendered, we use this method to refresh them at a defined time interval.

Example:

ADS GO HERE...

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { Component } from 'react';
import { AdSlot, DFPManager, DFPSlotsProvider } from 'react-dfp';

export default class RefreshableAds extends Component {
  componentDidMount() {
    this.interval = window.setInterval(
      () => { DFPManager.refresh('refreshable', 'refreshable-2'); },
      30000,
    );
  }

  componentWillUnmount() {
    window.clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        <DFPSlotsProvider dfpNetworkId="9999">
          <div>
            <AdSlot
              slotId="refreshable"
              sizes={[[728, 90], [300, 250]]}
              adUnit="test/refreshable"
            />
          </div>
          <div />
          <AdSlot slotId="refreshable-2" sizes={[[300, 250]]} adUnit="test/two" />
          <AdSlot sizes={[[300, 250]]} adUnit="test/three" />
        </DFPSlotsProvider>
      </div>
    );
  }
}

Notes:

  1. Line 22: Declare a toplevel <DFPSlotProvider>, this instance provides two things: 1) Basic configuration params that are shared among all the ads in the page and 2) Takes care of initializing ads as soon as the component gets mounted.
  2. Lines 20-29: We define three ad slots.
  3. Lines 6-9: using setInterval, we refresh the ad slots identified by the ids "refreshable" and "refreshable-2" every 30 seconds.
  4. Lines 13: clear internal loop before unmounting this component.