please tell me!
1 Replies
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;