Created
July 11, 2018 17:47
-
-
Save peleteiro/e966bb263bfb9a485bf1e964a917ff2a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global googletag */ | |
// tslint:disable no-any | |
import debounce from 'debounce-promise' | |
import _ from 'lodash' | |
import defer from 'lodash/defer' | |
import React from 'react' | |
type Props = { | |
id?: string | |
className?: string | |
path: string | |
sizes: Array<[number, number]> | |
location: string | |
} | |
const enableServices = debounce(() => { | |
googletag.cmd.push(() => googletag.enableServices()) | |
}, 100) | |
export default class DFPAdUnit extends React.Component<Props> { | |
slot: any = null | |
shouldComponentUpdate(nextProps: Props) { | |
const {path, sizes, location} = this.props | |
return !( | |
isEqual(path, nextProps.path) && // | |
isEqual(sizes, nextProps.sizes) && | |
isEqual(location, nextProps.location) | |
) | |
} | |
componentDidUpdate() { | |
googletag.cmd.push(() => { | |
this.slot.setCollapseEmptyDiv(false) | |
googletag.pubads().refresh([this.slot], {changeCorrelator: false}) | |
}) | |
} | |
componentDidMount() { | |
const {path, sizes} = this.props | |
const id = this.props.id || `das_${_.snakeCase(path)}` | |
const size = sizes.length === 1 ? sizes[0] : sizes | |
defer(() => | |
googletag.cmd.push(() => { | |
this.slot = googletag | |
.defineSlot(path, size, id) | |
.addService(googletag.pubads()) | |
.setCollapseEmptyDiv(true) | |
enableServices().then(() => { | |
googletag.display(id) | |
}) | |
}), | |
) | |
} | |
componentWillUnmount() { | |
googletag.cmd.push(() => googletag.destroySlots([this.slot])) | |
} | |
render() { | |
const {className, path, sizes} = this.props | |
const id = this.props.id || `das_${_.snakeCase(path)}` | |
return sizes.length === 1 ? ( // | |
<div id={id} className={className} style={{width: sizes[0][0] as number, height: sizes[0][1] as number}} /> | |
) : ( | |
<div id={id} className={className} /> | |
) | |
} | |
} | |
const isEqual = (v1: any, v2: any): boolean => (v1.equals ? v1.equals(v2) : _.isEqual(v1, v2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment