How to Add Adsense Ad Unit code in a React Component

To use Google Adsense Ad Unit 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 Ad Unit code in 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-114234437311277"
     data-ad-slot="1591512772"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Create a Component for Adsense Ad

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

  1. The Adsense Ad content loading script which looks like this:
  2. 
    <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>
    
  3. 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 enclosed 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:

    MyLeaderBoardAd.js
    
    import React, { Component  } from 'react'
    
    class MyLeaderBoardAd 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 MyLeaderBoardAd
    
  4. Now, to use the component, simply import it and use it as shown in the example below:
  5.