Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

javascript - How to embed google adsense in react js

I am beginner in reactjs and I want to embed google inline ads in loops. The ad is showing only at first time. When I inspect the element tag shows in loop. Can I please know how to solve this issue?

Google adsense code:-

 var ScheduleRow = React.createClass({
 var rows = _.map(scheduleData.schedules, function(scheduleList, i) {
  var divStyle = { display: "block"};  
  return (  
    <ins className="adsbygoogle"
        style={divStyle}
        data-ad-client="ca-pub-3199660652950290"
        data-ad-slot="6259591966"
        data-ad-format="auto" key={i}>
    </ins>
  ); 
 });

return (
    <span>
        {rows}
    </span>
);
});

Output:-

Output Image

Inspect Element Output:-

Inspect Element output

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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' }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...