In this article, we will see how to embed Google Adsense advertisement code in Reactjs.

Getting an ad unit code

To get the AdSense ad unit code, you need to create an ad unit. Follow the below steps to get an ad code.

  1. Sign in to your AdSense account.
  2. Click Ads.
  3. Click By ad unit.
  4. Click Display ads.
  5. Give a name to your ad unit. Always give a unique & descriptive name to your ad unit. This will help you to uniquely identify your ad unit.
  6. In the “Ad size” section, choose the size of the ads that you’d like to show. It can be either fixed or Responsive based on your requirements.
  7. Click Save and get code.

Integrate Adsense code in react component

In the place where you want to display the ad, we can use the dangerouslySetInnerHTML attribute to inject the Adsense code. Following is the example:

import React from 'react';

const AdSenseComponent = () => {
  const adSenseCode = `
    <!-- Replace this with your AdSense code -->
    <ins class="adsbygoogle"
    <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

  return (
    <div dangerouslySetInnerHTML={{ __html: adSenseCode }} />

export default AdSenseComponent;

Replace the adSenseCode variable with the code snippet that we got from AdSense in the above steps. Please make sure you replace the data-ad-client and data-ad-slot values with your own AdSense account details.

Import the Adsense script

In the React project’s index.html file, add the following script tag in the <head> section.

<script async src=""></script>

Categorized in:

Tagged in: