Ticker

6/recent/ticker-posts

How to Add Adsense code in a React Component?

How to Add Adsense code in a React Component

Using Google Adsense code in a React application does not require any additional plugin or library. We can directly embed Google Adsense Ad code in a React component and use it to display google ads.

In this tutorial, you will learn how to add Google Adsense code to a React component without using any library or plugin.


The Adsense Ad unit code that Google generates looks something like this:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-1142344322337311277"
data-ad-slot="1591512323772"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Create a Component for Adsense

Follow the steps below to create and use Adsense code as a React component:

1. The Adsense Ad content loading script looks like this:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Move the Ad content loading script into the body of your index.html page. The following shows how to do so:

   index.html  
<!DOCTYPE html>
<html lang="en">
.....
<body>
.......
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</body>
</html>
  • 2. Create a new react component and do as follows:

    - Move the   (adsbygoogle = window.adsbygoogle || []).push({})   code inside the componentDidMount() method and update it as (window.adsbygoogle = window.adsbygoogle || []).push({}).

    - Move the Ad code inside the render() method and update it as follows:

    • Update class attribute to className, wrap the value of the style attribute within double curly braces, and enclose only the style values with double quotes separated by a comma.

    • Wrap the Ad code with <div></div>.

    • Replace the value of data-ad-client and data-ad-slot attributes with your google generated values

The following code shows how to do so:

  AdComponent  

import React, { Component  } from 'react'

class
AdComponent extends Component {

componentDidMount() {
(window.adsbygoogle = window.adsbygoogle || []).push({})
}

render () {
return(
<div>
<ins className = "adsbygoogle"
style =
{ {display:"inline-block",width:"728px",height:"90px"} }
data-ad-client = "ca-pub-114234437311277"
data-ad-slot = "42837282224">
</ins></div>)
}
}

export default
AdComponent
3. Now, to use the component, simply import it and use it as shown in the example below:
import AdComponent from "your/path/AdComponent";

<AdComponent/>

Post a Comment

0 Comments