A react component for diplaying ads from Adsense
In this guide we will create a react component for displaying ads from Adsense. If you have your website approved by Google Adsense team, you probably have gotten some code snippets that they ask you to include in your project. However, if you are not having static HTML pages, but are instead client side rendering your project, it might not seen that trivial to get it to work. But don't worry, we will cover the necessary steps in this guide.
Code provided by Google
The code you have gotten probably looks similar the code below. And they ask you to add it to all the HTML pages you want this specific ad.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-{PUB_ID}" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-{PUB_ID}" data-ad-slot="{SLOT_ID}" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
First part in our index.html
The script at the top should be added to our index.html page.
<head> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-{PUB_ID}" crossorigin="anonymous" ></script> <body> <div id="root" /> </body> </head>
The rest should be added dynamically with our new component.
Create our component
Let's create our component. Create a new file called GoogleAd.tsx (or .jsx) and add the following code.
// @ts-nocheck import { useEffect } from "react"; interface IGoogleAd { className?: string; adAttributes: any; } export const GoogleAd = ({ className, adAttributes }: IGoogleAd) => { useEffect(() => { try { (adsbygoogle = window.adsbygoogle || []).push({}); } catch (err) {} }, []); return ( <div className={className}> <ins className="adsbygoogle" style={{ display: "block" }} data-ad-client="ca-pub-{PUB_ID}" {...adAttributes} ></ins> </div> ); };
There we go. The above component will be generic for the different types of ads that Adsense provides, and we will specify the necessary attributes with the adAttributes prop.
Example of consuming the component
If we want to consume the component, it could be done like below code. I will share two different ad types.
Example of a fluid responsive ad:
<GoogleAd className="myAdContainer" adAttributes={{ "data-ad-slot": SLOT_ID, "data-ad-format": "fluid", "data-full-width-responsive": "true", }} />
Example of an ad type that has specific layout definitions:
<GoogleAd adAttributes={{ "data-ad-slot": "SLOT_ID", "data-ad-format": "auto", "data-ad-layout-key": "-34+fg+21-9k-1m", }} />
And that's it. Now it should appear some ads where you place this component.
Outro
That's it for this guide. I hope you found this helpful and good luck with placing ads on you website.
Have a great day, and thanks for reading!