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

Top comments (1)

Collapse
 
lokersubang profile image
lokersubang.com

Thanks,, for information my website is loker subang builh with React Js

We want your help! Become a Tag Moderator.
Fill out this survey and help us moderate our community by becoming a tag moderator here at DEV.