Inject Inarticle ads or Google Adsense with React Js
Inject Inarticle ads or Google Adsense with React Js
by on on react

Inject Inarticle ads or Google Adsense with React Js

Ads are a good way of making money online, but most time we can find it difficult to use this ads in-between our blog contents when we use react Js or any front end library. Let's go ahead to fix this issue of using in article ads with react js.

First make sure you have jquery library installed in your react js app, then after that we are going to declare a global var. This global variable acts as a ghost variable which our app can only make use of if the component has mounted successfully. here is an example of the global variable.

declare var adsbygoogle: any;
declare var window: any;

This enable the JavaScript of react js to change these values when our components in a blog page, of course the compiled production build is already done loading.

Now to apply the google ads we make use of the useEffect hook provided by react js for functional based component, but for class based components we have componentDidMount.

Now to proceed, we have to make use of the JavaScript replace function. This is going to replace a text which trigger the ad show take for example, yours can be show-my-ad or something similar and then we replace that with a paragraph tag, here is an example of how to do that.

const newBody = body.replace("ad-spot", `



Note: You may put in between the

tag your add code.

Now let's go ahead and show our add using the componentDidMount or useEffect Hook.

useEffect(() => {

    setTimeout(() => {
      const adSpot = Jquery(".adspot");
      if (adSpot[0]) {
"display:block; text-align:center;"
      (adsbygoogle = window.adsbygoogle || []).push({});
    }, 2000);
  }, []);

Place the ad code on articles you want ads to appear, in between the HTML of your content

It can take 20-30 minutes for the ad to appear on the page. At first, the ad might show as a normal display ad, but it will soon be replaced by a native ad.

After this, your ad should display in between your blog post after the component has mounted successfully. I suggest also that you also make use of a setTimeout to avoid errors.