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, we will show you how to achieve this.

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

<script async src=""
<ins class="adsbygoogle"
     (adsbygoogle = window.adsbygoogle || []).push({});

Create a React component to include Google Adsense code

Follow these steps to create a component for including Google Adsense code:

  1. Configure Adsense Ad content loading script:
  2. The Adsense Ad content loading script which looks like this:

    <script async src=""

    Move the Ad content loading script into the body of your index.html page. For example:

    <!DOCTYPE html>
    <html lang="en">
        <script async src="" crossorigin="anonymous">
  3. Create a React component for Adsense Code:
    • Create a new class component that extends Component from react.
    • Add componentDidMount() method to the class.
    • Move the (adsbygoogle = window.adsbygoogle || []).push({}) code inside the componentDidMount() method and update it as (window.adsbygoogle = window.adsbygoogle || []).push({}).
    • Add render() method.
    • 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.

    Here's an example where MyLeaderBoardAd is the class name and MyLeaderBoardAd.js is the filename:

    import React, { Component  } from 'react'
    class MyLeaderBoardAd extends Component {
        componentDidMount() {
         (window.adsbygoogle = window.adsbygoogle || []).push({})
       render () {
            <ins className = "adsbygoogle"
                    style = { {display:"inline-block",width:"728px",height:"90px"} }
                    data-ad-client = "ca-pub-5231532077511212"
                    data-ad-slot = "1200201211"></ins>
    export default MyLeaderBoardAd
  4. Now, to use the component, simply import and use it as shown in the example below:
  5. import MyLeaderBoardAd from "your/path/MyLeaderBoardAd";
    <MyLeaderBoardAd />