Here’s a simple component that handles displaying ads, taking into account viewability
best practices.
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.