Here's a simple component that handles displaying ads, taking into account viewability best practices. (Thanks to Tracker1 for the comments here, which helped me tremendously in putting this together.)
import React from 'react';
import Waypoint from 'react-waypoint';
let instance = 0;
class Ads extends React.Component {
static propTypes = {
id: React.PropTypes.string,
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
adslot: React.PropTypes.string.isRequired
}
constructor() {
this.__id = 'ads-instance-' + ++instance;
this.displayAd = this.displayAd.bind(this);
}
get id() {
return this.props.id || this.__id;
}
componentDidMount() {
googletag.cmd.push(function() {
// Define the ad slot
googletag
.defineSlot(
this.props.adslot,
[this.props.width, this.props.height],
this.id
)
.addService(googletag.pubads());
// Start ad fetching
googletag.enableServices();
});
}
render() {
return (
<div style={{width:this.props.width, height:this.props.height}}>
<Waypoint onEnter={this.displayAd} />
<div id={this.id}></div>
</div>
);
}
displayAd() {
const id = this.id;
googletag.cmd.push(function() {
googletag.display(id);
});
}
}
export default Ads;
I've used react-waypoint to ensure proper viewability (not loading ads until users will see them). When the waypoint hits the bottom of the viewport as a user scrolls down to it, displayAd() shows the ad. The offset could be enhanced, but hopefully this will be a good starting point to give you the general idea.
If you have several ad slots on one page, you can use unique IDs in place of #ad-container
.