JavaScript / React.js

I recently needed to incorporate Google AdSense ads in a react.js application I was building. If you have used AdSense before, then you are acquainted with the code that is generated. For example

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- ad name -->
<ins class="adsbygoogle"
 style="display:block"
 data-ad-client="ca-pub-xxxxxxxxxx"
 data-ad-slot="xxxxxxxxxx"
 data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

So how do I use this with react?

Pasting everything directly into a component doesn’t work. So here is what I came up with.

Place the first script into the document <head>

ex. index.html
<head>
...
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">/script>
</head>

The next step is to create a GoogleAd component. The biggest change is placing the contents of the last script tag into the componentDidMount lifecycle event.

(adsbygoogle = window.adsbygoogle || []).push({});

A few other changes are required for react.js, such as changing class to className, converting the inline style tag from a string to an object, and I opted to wrap the adSense code in a div, which I could pass a style object to as well. The gist below contains some code to demonstrate.

This solution has worked for me, but if you experience any problems, just let me know and I’ll see if I can help.


Brandon Lehr

I'm Brandon Lehr, a web developer, machinist, and sometimes mechanic (when the truck breaks down). I guess you could say that I enjoy solving problems and building things.

PinewoodRaceDay Bootstrap Tabs, React Router, and the active class