DEV Community

Radheshyam Gupta
Radheshyam Gupta

Posted on

How To Add Google Adsense in Our React Website?

First We Add given Below AdSense code in our "index.html" File in between the tags like This.
You Get This Code From Your Google AdSense account.

<head>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXX"
     crossorigin="anonymous"></script>
 </head>
Enter fullscreen mode Exit fullscreen mode

*Now, Second We Create AdSense Component,Which We use in the place where we want to show Ads. AdsComponent.js *

import React, { useEffect  } from 'react';

const AdsComponent = (props) => {
    const { dataAdSlot } = props;  



    useEffect(() => {

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

        catch (e) {

        }

    },[]);



    return (
        <>
            <ins className="adsbygoogle"
                style={{ display: "block" }}
                data-ad-client="ca-pub-XXXXXXXXXXXXXXX"
                data-ad-slot={dataAdSlot}
                data-ad-format="auto"
                data-full-width-responsive="true">
            </ins>
        </>
    );
};

export default AdsComponent;
Enter fullscreen mode Exit fullscreen mode

And Now Finally time to show our ads in our React Pages Like this.

import './App.css';
import AdsComponent from './AdsComponent';

function App() {

//Note provide dataAdSlot value of your data-ad-slot which is your ad unit no.
    return (
        <>
            <h1>Place To show Google AdSense</h1>
           <AdsComponent dataAdSlot='X7XXXXXX5X' />
        </>

    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Well done! Finally Create AdSense Component For our React Website !

Drop some love by liking or commenting ♥

Reference w3schools

Download Source Code from GitHub Repository

Latest comments (7)

Collapse
 
mohsen9april profile image
Mohsen

not working !

Collapse
 
pramodk profile image
Pramod K 💻

Note: the google ad will not work on localhost

Collapse
 
radhe65gupta profile image
Radheshyam Gupta

Yes,it not work on Local,Because Googel Adsense Provide Ads on your given wesite url ,but when you use local ,Googel Adsense not get your provide website url

Thread Thread
 
pramodk profile image
Pramod K 💻

are there any other ways to test before we move to production?

Thread Thread
 
radhe65gupta profile image
Radheshyam Gupta

use google test Adsense Id

Collapse
 
radhe65gupta profile image
Radheshyam Gupta

can You Share Your Code

Collapse
 
Sloan, the sloth mascot
Comment deleted