Search code examples
reactjstypescriptnext.jsads

How to Implement Adsterra in next.js / react.js project


So I am trying to implement Adsterra Banner 300x50 on a ts/js reactjs + nextjs project, This is Adsterra provided script code for me to implement in the website:

<script type="text/javascript">
atOptions = {
    'key' : 'XXXXXX',
    'format' : 'iframe',
    'height' : 50,
    'width' : 320,
    'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.effectivecreativeformat.com/66e709b141fa8aa6d66cfda7e0b098a6/invoke.js"></scr' + 'ipt>');
</script>

And this is how I implement it, using 'Script/next'

<Script id="show-banner" strategy="afterInteractive">
{`
atOptions = {
    'key' : 'XXXXXX',
    'format' : 'iframe',
    'height' : 50,
    'width' : 320,
    'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.effectivecreativeformat.com/66e709b141fa8aa6d66cfda7e0b098a6/invoke.js"></scr'+'ipt>');
`}
</Script>

The problem I encounter here is, once the page load, everything got blank and white only. I hope someone can help me with experience in impementing Adsterra on a nextjs or react projects. thank you


Solution

  • So this is how I make it work

    import { useEffect, useRef } from 'react'
    export default function Banner(): JSX.Element {
        const banner = useRef<HTMLDivElement>()
    
        const atOptions = {
            key: 'KEY_HERE',
            format: 'iframe',
            height: 50,
            width: 320,
            params: {},
        }
        useEffect(() => {
        if (banner.current && !banner.current.firstChild) {
            const conf = document.createElement('script')
            const script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = `//www.highperformancedformats.com/${atOptions.key}/invoke.js`
            conf.innerHTML = `atOptions = ${JSON.stringify(atOptions)}`
    
            banner.current.append(conf)
            banner.current.append(script)
        }
    }, [banner])
    
        return <div className="mx-2 my-5 border border-gray-200 justify-center items-center text-white text-center" ref={banner}></div>
    }