React.js: Displaying Google Ads without using external packages

How to display Google Ads on your React.js Website


I have been working with React.js for quite a while now and all I can say about it, is that, it's a funny, funny framework when you start working with it. But once you get a hang of the structure and know how to work it, it will absolutely blow you mind (as it did mine). One of the aspects that I was particularly struggling with was integrating it with Google Ads.

It's quite embarrassing but the actual reason I was struggling is because I did not understand how to use traditional document-window etc. specific Javascript code (which I have been writing since forever) with React.js. This was the case until I discovered that most of this code is written inside componentDidMount(). Once this knowledge was acquired, it was off to the races.

The code below creates a component called `GoogleAd`. You can directly copy this code into a file with a name like google-ad.js. Import it with import GoogleAd from '../components/google-ad'; and use it in your code like any other React.js component which is like <GoogleAd /> (after changing the client and slot values, obviously). You should keep this in mind though. Google Ads do not work on localhost. Deploy them onto the Internet to see them flourish.