ReactJS: Cách thiết lập Adsense trên app React
Trước tiên ta đặt script sau vào index.html:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Tiếp theo ta tạo một component tên GoogleAds như sau:
import {useEffect} from 'react'
export default function GoogleAds({slot}){
useEffect(()=>{
const pushAd = () => {
try{
const adsbygoogle = window.adsbygoogle
console.log({adsbygoogle})
adsbygoogle.push({})
}catch(e){
console.error(e)
}
}
let interval = setInterval(()=>{
if(window.adsbygoogle){
pushAd()
clearInterval(interval)
}
},300)
return ()=>{
clearInterval(interval)
}
},[])
return (
<ins className='adsbygoogle'
style={{display:'block'}}
data-ad-client= 'ad-client-của-bạn'
data-ad-slot={slot}
data-ad-format= 'auto'
data-full-width-responsive="true"></ins>
)
}
Cuối cùng ta import component GoogleAds ở trên vào componnt mong muốn và đặt nó vào nơi mong muốn như sau:
<GoogleAds slot="slot-tương-ứng" />