Adding Google AdSense in React

Tiempo de lectura: 2 minutos

Today we’re going to learn how to add Google Adsense to React.

The first thing we need to do is to create an account on Google Adsense and obtain our page code.

Now we need to add the code inside our head like this:

    <head>
        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXX" crossOrigin="anonymous"></script>
    </head>

Where in ca-pub-XXXXXXXXXXXXX we must indicate our Google Adsense id.

And now we create our component GoogleAds.tsx

import React, { useEffect } from 'react';

declare global {
    interface Window {
        adsbygoogle: any;
    }
}

export enum DataAdLayout {
    IN_ARTICLE = 'in-article',
    IN_FEED = 'in-feed'
}

export enum AdSenseFormat {
    AUTO = 'auto',
    RECTANGLE = 'rectangle',
    HORIZONTAL = 'horizontal',
    VERTICAL = 'vertical',
    LEADERBOARD = 'leaderboard',
    SKYSCRAPER = 'skyscraper',
    LARGE_RECTANGLE = 'large_rectangle',
    RESPONSIVE = 'responsive',
    FLUID = 'fluid',
    LINK_UNIT = 'link_unit',
    AUTO_RELAXED = 'auto_relaxed',
}

interface AdSenseProps {
    client: string; // AdSense client ID
    slot: string; // AdSense slot ID
    dataAdLayout?: DataAdLayout;
    format: AdSenseFormat; // AdSense ad format
    dataFullWidthResponsive: boolean; // AdSense ad format
}

const GoogleAds: React.FC<AdSenseProps> = ({ client, slot, format, dataFullWidthResponsive, dataAdLayout }) => {
    useEffect(() => {
        // Load AdSense script only once
        const script = document.createElement('script');
        script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js`;
        script.async = true;
        document.body.appendChild(script);

        return () => {
            // Remove the script when the component unmounts
            document.body.removeChild(script);
        };
    }, []);

    useEffect(() => {
        // Show AdSense ad
        (window.adsbygoogle = window.adsbygoogle  []).push({});
    }, []);

    return (
        <ins
            className="adsbygoogle"
            style={{ display: 'block' }}
            data-ad-client={client}
            data-ad-layout={dataAdLayout}
            data-ad-slot={slot}
            data-ad-format={format}
            data-full-width-responsive={dataFullWidthResponsive}
        />
    );
};

export default GoogleAds;

To call an ad we must put:

<GoogleAds client="your-client-id" slot="your-slot-id" format={AdSenseFormat.AUTO} />

Remember they only work on the domain, on localhost the ads won’t load.

Leave a Comment