Adding an Adsense advert to a React app is a little tricky since you can't directly use the code generated for you by Google. However, you can create a component which allows you to show ads with a little bit of work.
Google's code
Google generates Adsense code for you, which looks a bit like this:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxx"
data-ad-slot="xxxxxxxxxx"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Move load script to HTML page
Firstly, move the first 'pagead2.googlesyndication.com' script into your HTML document (in this case, index.html
):
<!-- index.html -->
...
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</body>
</html>
Create advert component
Next, create a React component for the advert:
import React from 'react';</p>
export default class Ad extends React.Component {
componentDidMount () {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
render () {
return (
<div className='ad'>
<ins className='adsbygoogle'
style={{ display: 'block' }}
data-ad-client='ca-pub-xxxxxxxxxx'
data-ad-slot='xxxxxxxxxx'
data-ad-format='auto' />
</div>
);
}
}
There are a few changes you need to make:
- Put the
(window.adsbygoogle = window.adsbygoogle || []).push({});
line into thecomponentDidMount
method; - Stick the HTML into the render method;
- Change all
class
attributes intoclassName
; - Change
style
attribute so styles are wrapped with double curly brackets -style={{ display: 'block' }}
From here, you can replace the various attributes with props if needed.