Author -  Sai gowtham

How to Add Google ads to Gatsby & React apps

In this tutorial, we are going to learn about how to add google adsense ad code to your gatsby and react.js apps.

For understanding purposes, this tutorial is divided into 4 steps.

Step 1: Getting your Adsense ad code

Open your Google Adsense account and generate ad code, your code might look similar like below code.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="xxxxxxxxxxxx"
     data-ad-slot="xxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Step 2: Adding script tag to HTML file

For React sites

Open your index.html and add the script tag like in the below code.

index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="theme-color" content="#000000">
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  <title>React App</title>
  <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">  </script>
</head>

<body>
  <div id="root"></div>
</body>
</html>

For gatsby sites

Open your html.js file which is present inside your src folder.

Note: If you don’t find html.js file then run this command cp .cache/default-html.js src/html.jsin your terminal to get html.js file.

Now you need to update your html.js file with the below-highlighted lines.

html.js
import React from 'react'
import PropTypes from 'prop-types'

export default class HTML extends React.Component {
  render() {
    const ads = process.env.NODE_ENV === 'production' &&      <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" /> ;
    return (
      <html {...this.props.htmlAttributes}>
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          <meta name="theme-color" content="#fff" />
          {ads && ads}          {this.props.headComponents}
        </head>
        <body {...this.props.bodyAttributes}>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    )
  }
}

Step 3: Creating Adsense component

Now we are creating a GoogleAds component which helps us to use ads in different places.

create a new file called GoogleAds.js in your components folder and add the below code.

GoogleAds.js
import React, { Component } from 'react';

class GoogleAds extends Component {

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

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

export default GoogleAds;

In the above code, we created a GoogleAds component with this.props.slot so that we can pass the different slot ids at the time of using this component.

In data-ad-client add your client id.

Step 4: Using GoogleAds component

Now you can use this component anywhere in your app by adding an adsense slot id which you generated in step 1.

<div className="ad-class">
        {/* add your slot id  */}
     <GoogleAds slot="2434444" /></div>

Bonus tips

You can also create a similar component for the AdSense fixed ads.

GoogleFixedads.js
import React, { Component } from 'react';

class GoogleFixedads extends Component {

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

    render() {
        return (
                <ins className="adsbygoogle"                    style={this.props.style}                    data-ad-client="add-your-client-id"                >                </ins>        );
    }
}

export default GoogleFixedads;

Using GoogleFixedads component

In the below code you need to add your slot id and height, width.

<div className="fixed-ad">
         <GoogleFixedads
                  slot="234578578"                  style={{
                  display: 'inline-block',
                  width: '300px',                  height: '250px'                  }}
          />
</div>

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY