Skip to main content

⚛️ React Integration

This guide covers the integration of Magfi Ad Network in React applications.

Insert Script​

To ensure optimal ad performance and functionality, place the Ad SDK script within the <head> section of your HTML document.

<script src="https://gcdn.magfiads.com/magfi.min.js"></script>

Create Example Hook​

/hooks/useAdManager.js
  export const useAdManager = ({ AD_CODE }) => {
const adInstanceRef = useRef();

useEffect(() => {
adInstanceRef.current = window.MagfiAdNetwork.getInstance("YOUR_APP_CODE").add({ AD_CODE });
}, [AD_CODE]);

const manager = useCallback(() => {
if (!adInstanceRef.current) {
return {
show: () => {},
isReady: () => false,
addEventListener: () => {},
removeEventListener: () => {},
};
}
return adInstanceRef.current;
}, [AD_CODE]);

return manager;
};

Key points​

  • useRef: This hook is used to create a mutable reference to the ad instance. This allows the ad instance to persist between re-renders of the component.

  • useEffect: This hook is used to initialize the ad instance when the component mounts or when the AD_CODE prop changes.

  • useCallback: This hook is used to memoize the manager function, preventing unnecessary re-creations of the function.

  • manager function: This function returns the ad instance if it's available, or a fallback object with empty functions if the ad instance is not yet ready.

  • Type definitions (TypeScript): The TypeScript version includes type definitions for AdCallbacks, AdEventName, and AdInstance to ensure type safety.


How to use​

  1. Import the useAdManager hook into your component.

  2. Call the hook with the AD_CODE as an argument.

  3. Use the returned manager object to interact with the ad instance (e.g., manager.show(), manager.addEventListener()).

/pages/home.js
import { useAdManager } from './hooks/useAdManager';
import { useEffect } from "react";

const MyComponent = () => {
const ad1 = useAdManager({ AD_CODE: 'YOUR_AD_CODE' });

//Listener example
useEffect(() => {
ad1().addEventListener("onReady", () => {
console.log("ad ready");
});
}, [ad1]);

const handleShowAd = () => {
if (ad1().isReady()) {
ad1().show({
onClosed: () => {
// Handle ad close
},
onSkip: () => {
// Handle ad skip
}
});
}
};

return (
<div>
{/*... other component content...*/}
<button onClick={handleShowAd}>Show Ad</button>
</div>
);
};