React DFP Documentation

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

 Refreshable ads 1

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(): 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
35
36
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(); },
      30000,
    );
  }

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

  render() {
    return (
      <div>
        <DFPSlotsProvider dfpNetworkId="9999">
          <div>
            <AdSlot
              sizes={[[728, 90], [300, 250]]}
              adUnit="test/non-refreshable"
              shouldRefresh={() => false}
            />
          </div>
          <div />
          <AdSlot sizes={[[300, 250]]} adUnit="test/refreshable" />
        </DFPSlotsProvider>
      </div>
    );
  }
}
if (typeof window !== 'undefined') {
  DFPManager.load();
}

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 24-29: We define a non-refreshable ad. This will not be refreshed when calling DFPManager.refresh(); . Notice that the prop shouldRefresh receives a function that gets evaluated syncrhonously; this function is called by DFPManager.refresh() each time this last one is executed, the component is only refreshed when this fcn returns true.
  3. Line 32: define a refreshable ad-slot using the <AdSlot> component.
  4. Lines 9-11: setup an interval loop that refreshes the ads rendered in this page every 30 seconds.
  5. Lines 15: clear internal loop before unmounting this component.