How to embed google adsense in react js

六月ゝ 毕业季﹏ 提交于 2019-11-30 02:28:56
jpgbarbosa

This seems a duplicated question. You can find it in here. But I think it isn't 100% clear. So, I came across once with this blog post which is more clear.

From Google you have this:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>

<ins class="adsbygoogle"
      style="display:block"
      data-ad-client="ca-pub-12121212"
      data-ad-slot="12121212"
      data-ad-format="auto"/>

<script>
  (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Now, in your react app:

Include the following snippet in your index.html

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Create your react component like:

import React from 'react';

export default class AdComponent extends React.Component {
  componentDidMount () {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  }

render () {
    return (
        <ins className='adsbygoogle'
          style={{ display: 'block' }}
          data-ad-client='ca-pub-12121212'
          data-ad-slot='12121212'
          data-ad-format='auto' />
    );
  }
}

Now, to render it multiple times you can simply wrap the ins html tag with an iterator like map. However, I don't fully understand your need here.

If you want to show them all at once, then do your map like this.

If you want to randomise your ad, add a state to your component and a tick state so that it can re-render every X seconds. Check it in this SO answer

Notes:

  1. From you google sense add, rename class attribute to className
  2. Update style attribute to be wrapped like this: style={{ display: 'block' }}
Seunghun Sunmoon Lee

Answer by @jpgbarbosa is great. I'll add better practice for Server Side Rendered React applications which have multiple pages, for scalability, I suggest you use this method to keep code base maintainable.

export default class HomePage extends React.Component {
  componentDidMount() {
    const installGoogleAds = () => {
      const elem = document.createElement("script");
      elem.src =
        "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
      elem.async = true;
      elem.defer = true;
      document.body.insertBefore(elem, document.body.firstChild);
    };
    installGoogleAds();
    (adsbygoogle = window.adsbygoogle || []).push({});
  }

  render() {
    return (
      <ins className='adsbygoogle'
           style={{ display: 'block' }}
           data-ad-client='ca-pub-12121212'
           data-ad-slot='12121212'
           data-ad-format='auto' />
    );
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!