How to integrate EZOIC with ReactJs and NextJs

Last updated : 29 April 2022

1. Overview

The approach to integrating Ezoic ads with ReactJs or NextJs based websites is different from traditional request/response based websites. This article explains how to integrate Ezoic with ReactJs or NextJs based websites. This method works for all the Ezoic ads embedded on the page. Including the ads embedded in a post body and rendered as dangerouslySetInnerHTML.

Check out our other articles on analytics and Google Adsense.
Next js google tag manager: 3 ways to use Google analytics in Nextjs
React js google tag manager: React Google analytics problem solved
How to use google adsense in Next Js

2. Why do Ezoic ads need a different approach with ReactJs and NextJs?

If you integrate Ezoic with Nextjs in the traditional way, the ads will show in the initial page load. Any internal navigation that happens with the <Link> tag will not trigger ads. That is because Ezoic ad units need a page refresh to work. The <Link> tag doesn't cause a full page refresh.

3. Steps to integrate

We assume that your page is rendered with embedded ad units. Ad units are divs with a specific id with a unique ad id appended to it.

<div id="ezoic-pub-ad-placeholder-109"> </div>

This appended id is used to identify the ad unit and is referred to as placeholders. In the above ad unit, 109 is the placeholder.

3.1 Insert Ezoic standalone Javascript

Select a page resource common to all the pages of your application. That can be the _document.js, _app.js, or any layouts that you use. Insert the below script.

<script src="//www.ezojs.com/ezoic/sa.min.js"></script>

3.2 Insert the ezstandalone Javascript code to enable ads

The next step is to insert the Javascript code that define and enable all the ads embeded in the page. The ezstandalone is a function defined in the file sa.min.js An important point to note here, is that ezstandalone function should only be executed after all ad units are loaded on the page. Therefore, we will use it in the useEffect hook.

useEffect(() => {
    ezstandalone.define(109,110);
      if (!ezstandalone.enabled) {
        ezstandalone.enable();
        ezstandalone.display();
      }
      else {
        ezstandalone.refresh();
      }
},[])
ezstandalone.define() defines the ad placeholders. You should pass all the ad placeholders as an integer array to this function.
ezstandalone.enable() enables the placeholders defined in the above step. ezstandalone.display() displays the ads in placeholders.
ezstandalone.refresh() is triggered with each new page-view with internal navigation.

It is important to make sure all the placeholders are defined and enabled by double checking your ezstandalone.define(109,110) statement to confirm that.

Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments