Why Google AdSense not showing with Reactjs? - reactjs

I'm trying to implement a simple banner Ad with Google AdSense inside my React website. I used create-react-app.
I've created a component wrapping the banner:
import React, { Component } from 'react';
class AdBanner extends Component {
componentDidMount () {
(window.adsbygoogle = window.adsbygoogle || []).push({});
console.log('DID IT!!');
}
render () {
return (
<ins className="adsbygoogle"
style={{ display: "block"}}
data-ad-format="fluid"
data-ad-layout-key="-fb+5w+4e-db+86"
data-ad-client="ca-pub-xxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxx">
</ins>
);
}
}
export default AdBanner;
And I've added the following script inside the <head> tag of my index.html file
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
## The problem ##
The Ad is not showing up in any way! The compiler is ok and browser does not give any message in the console (apart of 'DID IT!'. I've created the Ad in the console two days ago.
I've tried also deactivating React strict mode.
Thankssssss

When you say ad is not showing up - do you see empty white rectangle where ad should be? Also do you see googleads.g.doubleclick.net/pagead/ads? requests in network tab? If so - how many? If you see 2 then ad requests are made and what might be happening is that AdSense didn't find a good ad, which is normal. You can also try adding data-adtest="on" to the <ins> tag which might help to force an ad.

Related

Getting "Key not Found:" while accessing static website on s3

I have a working website which is developed in react and is hosted as a static site on AWS-S3. Our home page route is /home however when we try to access it, we get the following error:
Message: The specified key does not exist.
Key: home/home
RequestId: 0CJ72YSRVM1VR7DT
HostId: EnusXIGM/BWUeBk2Y+jjW2XFYtKjpFB66wf2n9om5L/+yX52JQUviK5ZLPJW6U0moywqGuIBc5M=
so, in the root folder, we have put a index.html in the root folder with the following content.
import React from "react";
import { useNavigate } from "react-router-dom";
const Coverpage: React.FC = () => {
const navigate = useNavigate();
return (
<>
<div>I am cover page!</div>
<button onClick={() => navigate("/home")}>Click me to navigate to homepage!</button>
</>
);
};
export default Coverpage;
and the navigation works.
I really need help to find a way where when the user access the site http://xxxx, the site directly navigate to http://xxxx/home and the site opens as desired.
Appreciate your help. not sure if we can do it at reactjs level or AWS s3
The solution is to configure AWS to rewrite most URLs to your React's index.html.
Create a CloudFront distribution which distributes the S3 bucket.
Ensure the distribution's Default Root Object is set to index.html.
Create a CloudFront function with the code below. This rewrites all requests to index.html except for requests to /static/*.
function handler(event) {
var request = event.request;
var parts = request.uri.split('/');
if(parts[1] != 'static'){
request.uri = '/index.html';
console.log('Rewriting: ' + request.uri);
} else {
console.log('Not Rewriting: ' + request.uri);
}
return request;
}
Go to the CF distribution then open the default behaviour (or create it if needed) and at the bottom, associate the function as a View Request type
Now you can visit the CF Distribution's URL (or your domain if configured) with any path and the React app will show.
The other option is to simply set the S3 bucket's Error Document to index.html, but this is very hacky and not recommended. Page visits will show the React app but will have undesirable 404 error codes.

How to force Gatsby to redirect a specific URL path to an external site?

I have a Gatsby site and due to some specific requirements, I need to redirect anyone who attempts to hit a specific URL path, for which there is no page, to an external site. This URL path is not a page within the site, but it's something that a user may be inclined to type due to documentation that is out of my control.
Here's an example: Let's say the site is located at https://www.example.com. A user may visit https://www.example.com/puppies, which does not exist. My file structure does not contain a src/pages/puppies.js file. However, when that URL is entered, I need to redirect the user to another site altogether, such as https://www.stackoverflow.com.
I haven't used Gatsby to that extent to know it has a configuration for this, so someone else may correct me. The way I would handle this is through the hosting provider where your app is.
For example, if you are using Netlify:
Create a _redirects file with the following content:
/* /index.html 200
Or
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
This will cause all https://yourwebsite.com/IDontHaveThisRoute to fallback to /index.html where your .js is loaded.
I provided the Netlify example only to give you the basic idea of how it can be done through the hosting provider of your choice. I would look into configurations I can put into redirects where my domain is deployed.
Thanks to Paul Scanlon he mentioned using onRouteUpdate in Gatsby and it works like a charm
import { navigate } from 'gatsby';
export const onRouteUpdate = ({ location }) => {
if (location.pathname === '/dashboard') {
navigate('/dashboard/reports');
}
};
This question helped point me in the right direction. I was able to get it to work using Gatsby's componentDidMount() to force a redirect as shown below, using a new file called puppies.js to "catch" the path typed by the user:
// puppies.js
import React, { Component } from 'react'
class Puppies extends Component {
componentDidMount() {
window.location.replace("https://www.stackoverflow.com");
}
render() {
return <div />
}
}
export default Puppies

Not able to connect AdSense to Gatsby blog

I've been trying to connect my AdSense account with my Gatsby blog and it seems impossible. AdSense is asking me to place this code between the head tag of my html
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
I've tried gatsby adsense plugins and other things and AdSense keeps telling me the code is not in the website. Since the website is hosted in S3, I downloaded the generated index.html and changed the code and re uploaded it. I think the problem is due to an added attribute called data-checked-head to the script tag, so even though I add the code above, what I see in the browser is this:
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" data-checked-head="true"></script>
If this code is what AdSense sees, then of course he doesn't recognize it. Does anyone know what can I do in this case?? Or why is this attribute even there?? Thanks
I can't answer about the details of AdSense but I have had problems with meta tags in the head of HTML myself. Here's two possibilites to debug your code in regards to Gatsby:
Many plugins are disabled by default in development mode. Try gatsby build and gatsby serve and then check if it works with plugins.
Use react-helmet to place your script tag in the head of HTML. Use gatsby build and gatsby serve for testing this as well.
You can use gatsby-plugin-google-adsense for displaying ads on your site.
The best way I found is from this article, which suggest a simple React implementation of Google AdSense.
In your gatsby-ssr.js file:
const React = require('react')
const HeadComponents = [
<script
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXX"
crossOrigin="anonymous"
async
/>,
]
exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
setHeadComponents(HeadComponents)
}
Then you create a Banner component to include in your Gatsby.js pages:
const Banner: React.FC<BannerProps> = ({
className,
style,
layout,
format,
client = 'ca-pub-XXXX',
slot,
responsive,
layoutKey,
}) => {
useEffect(() => {
try {
const adsbygoogle = window.adsbygoogle || []
adsbygoogle.push({})
} catch (e) {
console.error(e)
}
}, [])
return (
<div className="banner-container">
<ins
className="adsbygoogle"
style={style}
data-ad-layout={layout}
data-ad-format={format}
data-ad-client={client}
data-ad-slot={slot}
data-ad-layout-key={layoutKey}
data-full-width-responsive={responsive}
/>
</div>
)
}
Full article here.

React Native: How do you get a Moneris transaction to return to app?

I'm processing a transaction with Moneris in my React Native app in a WebView. The URL in my WebView contains the credentials of my Hosted PayPage Configuration as URI parameters. When creating that configuration on the Moneris site, I need to provide the URL for the hosted paypage to redirect to once the transaction is complete. When I enter something like https://www.google.ca/ as the callback, it works fine, but I don't know what callback URL I'd need to enter to return to my app.
What I Want To Know:
What is the callback URL I'd need to use in order to return to a React Native app?
WebView is just a component inside your app, so you are never leaving your app. First, confirm that page is rendered in a WebView as opposed to launching browser as a separate app and opening a page there (in this case you can't go back to your app programmatically). Then, if you are actually using a WebView component, you could, for example, do the following: add NavigationState listener to your WebView, and read the url the WebView navigates to and take action accordingly
class MyComponent extends React.Component{
onNavigationStateChange = (navState) => {
if (navState.url === 'https://www.yoursite.com') {
// user just got redirected to requested site
// do something in react-native app now, for example
// close this component and show another one
}
}
render(){
return <View>
<WebView
...
onNavigationStateChange={this.onNavigationStateChange}
/>
</View>
}
}

Fetch As Google Is Showing Blank Page - Reactjs

I have a Reactjs (v.16.6.3) page which its SEO is important to be indexed by Google. Therefore, I checked it with Fetch as Google tool to know what Google-bot renders from this page.
However, google shows nothing and only depicts a blank page to me!
I have added 'babel-polyfill' to fulfill es6-es7-es8 requirement and make google-bot happy since I have used async-await (es8) approach in ComponentDidMount (to load async data in this lifecycle method) and other methods. Also popular arrow functions have been used though and result is nothing in Fetch as Google again!
I even get no result while importing some flat data (like the following I have written) which are only imported from another module and put directly to render method (not in componentDidMount). I have checked and found that they exist to main.chunk.js and Google should read and render them adequately but nothing happened!
export const sampleData01= [
{name: sampleName01,
lastName: sampleLastName01,
image: sampleImage01
},
{name: sampleName02,
lastName: sampleLastName02,
image: sampleImage02
}
]
export const anotherData02= [
{name: anotherName01,
lastName: anotherLastName01,
image: anotherImage01
},
{name: anotherName02,
lastName: anotherLastName02,
image: anotherImage02
}
]
-----------
import React, {Component} from 'react'
import {sampleData01} from './tempData'
import Helmet from "react-helmet";
class SampleClass extends Component {
state = {...something , loading:false}
async componentDidMount = ()=> {
this.setState({loading:true})
...await fetch something
this.setState({loading:false})
}
}
render(){
const data = sampleData01.map(item => {
<li>
{item.name}
</li>
}
return (
<div className="...">
<Loading loading={this.state.loading}/>
<div className="...">
<Helmet link={....} title={....} meta={....} />
<ul>
{data}
</ul>
</div>
</div>
)
}
export default SampleClass
eveything is working fine on both dev and production mode. I have checked every possible ways such as importimg es6-shim, isomorphic-fetch, url-search-params-polyfill, whatwg-fetch and got no result! I have read in some article that google might use phantomjs for rendering page. I have checked out page with phantomjs by myself in the web (not local) and it shows and renders perfectly fine. I have read lots of articles say there is no issue with Google search and SPAs while I am seeing something else! It seems I should shift to SSR for more convenient way to ensure having SEO friendly page.
I have tried so many dirty hacks to improve SEO for Client Side rendering website but in the end SSR was the only option. Either make your own SSR project using or using Razzle (https://github.com/jaredpalmer/razzle) or Next.js (https://github.com/zeit/next.js/)

Resources