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="//"></script>
<!-- ad name -->
<ins class="adsbygoogle"
(adsbygoogle = window.adsbygoogle || []).push({});

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
<script async src="//">/script>

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