Languages
[Edit]
EN

React - use Google Ads / GPT

6 points
Created by:
jarlh
635

In this short article, we would like to show how to use Google Ads / GPT in React.

Google Ads / GPT displayed with open console.
Google Ads / GPT displayed with open console.

Note: read official documentation to know more about GPT.

Hints:

  • run below code under your domain and use proper links and sizes for slots to see the effect,
  • if you are using AdBlock/uBlock/etc. disable it - you can find AdBlock/uBlock/etc. detection test here,
  • if you are interested GPT Vanilla JS source code version go to this article.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    div {
    	margin: 5px;
    }
    
  </style>
  
  <!-- Required only to run React code in this example -->
  <script src="https://unpkg.com/react/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  
  <!-- Google Ads / GPT import - attach it to yours project -->
  <script src="https://www.googletagservices.com/tag/js/gpt.js"></script>

</head>
<body>
  <div id="root"></div>
  <!-- copy below script body to React project -->
  <script type="text/babel">

	//Note: Uncomment import lines during working with JSX Compiler.
    
	// import React from 'react';
    // import ReactDOM from 'react-dom';
    
    const googletag = window.googletag || (window.googletag = { cmd: [] });
    
    const createScope = (action) => action && action();
    
    const GPTAdsManager = createScope(() => {
        let initialized = false;
        const initializeAds = (initialLoading = false, singleRequest = true) => {
            if (initialized) {
               	return;
            }
            initialized = true;
            googletag.cmd.push(() => {
                const pubads = googletag.pubads();
                if (!initialLoading) {
                  	pubads.disableInitialLoad();
                }
                if (singleRequest) {
                  	pubads.enableSingleRequest();
                }
                googletag.enableServices();
          	});
        };
        const createSlot = (adPath, adWidth, adHeight, elementId) => {
            initializeAds(); // only if not initialized yet
            let slot = null;
            googletag.cmd.push(() => {
                const size = adWidth & adHeight ? [adWidth, adHeight] : ['fluid'];
                const tmp = googletag.defineSlot(adPath, size, elementId);
                if (tmp) {
                    slot = tmp;
                    tmp.addService(googletag.pubads());
                }
            });
            const display = () => {
                if (slot) {
                    googletag.cmd.push(() => {
                        const pubads = googletag.pubads();
                        pubads.refresh([slot]);
                    });
                }
            };
            const refresh = () => {
                if (slot) {
                    googletag.cmd.push(() => {
                        const pubads = googletag.pubads();
                        pubads.refresh([slot]);
                    });
                }
            };
           	const destroy = () => {
                if (slot) {
                    const tmp = slot;
                    googletag.cmd.push(() => {
                        const pubads = googletag.pubads();
                        googletag.destroySlots([tmp]);
                    });
                    slot = null;
                }
            };
            return { display, refresh, destroy };
        }
        return { initializeAds, createSlot };
    });

    let adCounter = 0;

    const Ad = ({ path, width, height }) => {
    	const id = React.useMemo(() => `div-gpt-ad-${++adCounter}`, []);
        React.useEffect(() => {
            const slot = GPTAdsManager.createSlot(path, width, height, id);
            slot.display();
            // slot.refresh(); // forces Ad reloading
            return () => {
               	slot.destroy();
            };
        }, [path, width, height]);
		return (
          <div id={id} />
        );
    };

	// Usage example:

	// somewhere in the code...
	GPTAdsManager.initializeAds(false, true);        

	// uncomment below 3 lines to open GPT Ads console
    // window.googletag.cmd.push(() => {
    //     window.googletag.openConsole();
    // });

    const App = () => (
	  <div className="App">
	    <Ad path="/6355419/Travel/Europe/header" width={300} height={50} />
        <Ad path="/6355419/Travel/Europe/body" width={300} height={250} />
        <Ad path="/6355419/Travel/Europe/body" width={300} height={250} />
        <Ad path="/6355419/Travel/Europe/footer" width={300} height={50} />
	  </div>
	);

	const root = document.querySelector('#root');
	ReactDOM.render(<App />, root );

  </script>
</body>
</html>

Note: be sure that Ad size has always the same size to prevent unnecessary Ad recreation - or change it consciously according to new slot configurations.

References

  1. API - Google Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - use Google Ads / GPT
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join