Adding AdSense Ads to Gatsby Blog

Posted on May 25, 2022 (1 minute read)

by Ivan Campos

In your site's Layout component, add the adsbygoogle script to HTML Head by using the react-helmet npm package.

import React from "react" import Header from "./header" import Footer from "./footer" import "../styles/style.scss" import { Helmet } from 'react-helmet' const Layout = props => { return ( <React.Fragment> <Helmet> script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" /> </Helmet> <div className="wrapper"> <Header /> {props.children} </div> <div className="footer"> <Footer /> </div> </React.Fragment> ) } export default Layout

Once your Layout is saved, add a component for your Google Ads with your client number.

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= 'ca-pub-YOUR_CLIENT_NUMBER' data-ad-slot={this.props.slot} data-ad-format= 'auto' data-full-width-responsive="true" > </ins> ); } } export default GoogleAds;

Finally, inside your blog post, import the GoogleAds component and return the GooglAds tag with your slot number.

import GoogleAds from "../components/GoogleAds"; const BlogPost = props => { return ( <Layout> <div> <h1>{props.data.markdownRemark.frontmatter.title}</h1> <span> Posted on {props.data.markdownRemark.frontmatter.date}{" "} ({props.data.markdownRemark.timeToRead} minute read) </span> <div> <GoogleAds slot="YOUR_SLOT_NUMBER" /> </div> <div dangerouslySetInnerHTML={{ __html: props.data.markdownRemark.html }} className="blog-post" > </div> </div> <div className="comments"> <Comments /> </div> </Layout> ) }

Comments