I’ve been following this example:
https://www.jamesbaum.co.uk/blether/using-google-adsense-with-react/
I have this component:
import React from "react"; export default class AdBanner extends React.Component { componentDidMount () { (window.adsbygoogle = window.adsbygoogle || []).push({}); } render () { return ( <div className='ad'> <ins className='adsbygoogle' style={{ display: 'block' }} data-ad-client='div-gpt-ad-1536172937182-0' data-ad-slot='/164808479/Leaderboard' data-ad-format='auto' /> </div> ); } }
I have this on my index.html
:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
When I run my test page I get no ads rendering and this error:
I have no idea what this error means or how to resolve it.
It’s critical to mention that the client and slot IDs work perfectly in a non-react test app So something else must be wrong here.
also, I am testing this via localhost:8080 — which works for the non react test app, so I do not think it’s a localhost/google ads issue.
IN OUR OLD NON-REACT APP
in our <header>
:
<script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script> <script> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; </script> <script> googletag.cmd.push(function() { googletag.defineSlot('/164808479/Leaderboard', [728, 90], 'div-gpt-ad-1536172937182-0').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script>
in our <page.php>
:
<!-- /164808479/Leaderboard --> <div id='div-gpt-ad-1536172937182-0' style='height:90px; width:728px;'> <script> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1536172937182-0'); }); </script> </div>
This produces a working ad right now, even from 127.0.0.1:80
(running via Docker) Our problem is our lack of ability to make this work inside a React component.
Advertisement
Answer
You are getting HTTP 400 (i.e. Bad Request) because the data being sent to google ad servers seems wrong.
The data-ad-client
value should have the format like ca-pub-00000000000000
which is obtained from adsense administration page. (I believe this is not your case!!!)
The data you provide, div-gpt-ad
seems as an id of a div
for google publisher tag which has the id /164808479/Leaderboard
. So in order to use that in your react application properly you can use this library: https://github.com/nfl/react-gpt
So below you can find the modified code which is suitable for your case. Just add react-gpt
to your react application.
import React from "react"; import {Bling as GPT} from "react-gpt"; GPT.enableSingleRequest(); export default class AdBanner extends React.Component { render () { return ( <div id="div-gpt-ad-1536172937182-0"> <GPT adUnitPath="/164808479/Leaderboard" slotSize={[728, 90]} /> </div> ); } }
You can see the above code working beautifully in this link: https://codesandbox.io/embed/determined-bash-k30nq