How to render the fresh google ad on every page in react app
We generally use ins element to show google ads. But on navigation, react uses same ins element that was created before.
To address the issue of React reusing the same <ins>
element without rendering a new ad, you can force React to re-render the ad component by using a unique key for the <ins>
element. This approach ensures that React treats it as a new element on route changes.
Here’s how you can achieve this:
Step-by-Step Implementation
- Create a Component to Handle Ads: This component will use a unique key for the
<ins>
element to ensure it is treated as a new element on each route change.
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
const AdSense = () => {
const location = useLocation();
const [adKey, setAdKey] = useState(0);
useEffect(() => {
const loadAds = () => {
if (window.adsbygoogle) {
window.adsbygoogle = window.adsbygoogle || [];
window.adsbygoogle.push({});
}
};
// Check if the AdSense script is already loaded
if (!document.querySelector('script[src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"]')) {
const script = document.createElement('script');
script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
script.async = true;
script.onload = loadAds;
document.body.appendChild(script);
} else {
loadAds();
}
// Change the key to force a re-render of the ad
setAdKey(prevKey => prevKey + 1);
}, [location]);
return (
<ins
key={adKey} // Unique key to force re-render
className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
data-ad-slot="XXXXXXXXXX"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
);
};
export default AdSense;
- Use the AdSense Component in Your Pages: Import and use the
AdSense
component in your page components.
import React from 'react';
import AdSense from './AdSense';
const HomePage = () => (
<div>
<h1>Home Page</h1>
<AdSense />
</div>
);
const AboutPage = () => (
<div>
<h1>About Page</h1>
<AdSense />
</div>
);
export { HomePage, AboutPage };
- Set Up Routing: Set up routing in your application using
react-router-dom
.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { HomePage, AboutPage } from './pages';
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/about" component={AboutPage} />
</Switch>
</Router>
);
export default App;
Explanation
- AdSense Component: The
AdSense
component uses a unique key for the<ins>
element to force React to re-render it on route changes. The key is incremented whenever the route changes, ensuring that React treats it as a new element. - Effect Hook: The
useEffect
hook runs whenever the route changes (becauselocation
is a dependency). This ensures that the key is updated and ads are refreshed on each route change.
Published on: Aug 07, 2024, 09:32 AM