Techiio-author
Started by Natasha JonesMay 6, 2022

Open
How can i link google adsense with react js website?

7 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 7 VIEWES SHARE

please tell me!

1 Replies

Techiio-commentatorUtsab Das replied 3 months ago0 likes0 dislikes

When you have a blog or website which can earn money from Google AdSense (Google has approved) and it was build with ReactJS. How to add Google AdSense to your React application? For this question, today we'll share you about the way to do that.

Step 1:Get your Google AdSense script code and add it into your HTML file, place the code inside the head tag like this:

<script>
async
data-ad-client="ca-pub-yourGoogleAdId"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
</script>

Step 2:Create Google Adsense Component to re-use in wherever you want:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

const googleAdId = 'ca-pub-yourGoogleAdId';

class GoogleAd extends Component {
googleInit = null;

componentDidMount() {
const { timeout } = this.props;
this.googleInit = setTimeout(() => {
if (typeof window !== 'undefined')
(window.adsbygoogle = window.adsbygoogle || []).push({});
}, timeout);
}

componentWillUnmount() {
if (this.googleInit) clearTimeout(this.googleInit);
}

render() {
const { classNames, slot } = this.props;
return (
<div className={classNames}>
<ins
className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client={googleAdId}
data-ad-slot={slot}
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
</div>
);
}
}

GoogleAd.propTypes = {
classNames: PropTypes.string,
slot: PropTypes.string,
timeout: PropTypes.number,
};

GoogleAd.defaultProps = {
classNames: '',
timeout: 200,
};

export default GoogleAd;

the Component above, we use 3 props to handle your Google Adsense: - classNames: String => To add custom class name to style your Google Ads - slot: String => To insert data-ad-slot that you get from Google AdSense - timeout: Number (default is 200 milliseconds) => To time delay for your Ads after the page rendered (optional)

Step 3:Add the GoogleAd component into your site where you'd like to display:

import React, { Component } from 'react';
import GoogleAd from 'components/GoogleAd';

class YourPage extends Component {
render() {
return (
<div>
<GoogleAd slot="989038934" classNames="page-top" />
<div>Page Content...</div>
<GoogleAd slot="394738798" timeout={1000} classNames="page-bottom" />
<div>Page Content...</div>
</div>
);
}
}

export default YourPage;
You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance