import React, { useEffect, useRef } from 'react'; interface GoogleAdProps { slotId?: string; className?: string; format?: 'auto' | 'rectangle' | 'vertical' | 'horizontal'; } const GoogleAd: React.FC = ({ slotId, className, format = 'auto' }) => { const adRef = useRef(null); const hasRequestedAd = useRef(false); // Use the provided ID or the placeholder const effectiveSlotId = slotId || "1234567890"; const isPlaceholder = effectiveSlotId === "1234567890"; useEffect(() => { // If it's a placeholder, do not attempt to fetch an ad (prevents 400 errors) if (isPlaceholder) return; // Prevent double execution in React Strict Mode if (hasRequestedAd.current) return; try { // @ts-ignore const adsbygoogle = window.adsbygoogle || []; // Safety Check: Only push ad if the element is actually visible in the DOM if (adRef.current && adRef.current.offsetWidth > 0 && adRef.current.innerHTML === "") { adsbygoogle.push({}); hasRequestedAd.current = true; } } catch (e) { console.error("AdSense error:", e); } }, [isPlaceholder]); // Render a placeholder box if no valid Slot ID is provided if (isPlaceholder) { return (
Ad Space Configure Slot ID in Code
); } return (
); }; export default GoogleAd;