Issue in integrating GoogleMaps in React App - reactjs

I am trying to integrate googlemaps in my React App.But it returns the following error in javascript console.
The javascript console returns the following error while trying to integrate Google Maps.How can I resolve that issue?
[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive.
js?key=APIKEY:99
[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.
util.js:40
[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking event handler as 'passive' to make the page more responsive.
util.js:40
[Violation] Added non-passive event listener to a scroll-blocking 'touchmove' event. Consider marking event handler as 'passive' to make the page more responsive.
How can I display Google Maps in my browsers?

I have a working solution with a different package.
However, there are a few issues with your code example, so please see if you can utilise these suggestions for resolving several issues with it.
1. Google maps script in head section
Unlike stylesheets and fonts, scripts should be loaded at the end of the body, for peformance reasons, as they will otherwise be loaded before the content, prolonging the page load.
Also, don't forget to include page title and other things, that usually help you with SEO, which are missing in your example.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<title>page title</title>
</head>
<body>
<div class="container"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY" type="text/javascript"></script>
<script src="./bundle.js"></script>
</body>
</html>
2. Map itself & User details
I've previously successfully used another package called 'react-google-maps' that seems to be working properly at this moment, so I'll add an example with that one inside the UserDetail example
Considering that you only have a render method for UserDetails, I would suggest that you use a pure functional component here.
Also, there are a few things you can do here to help with code brevity, and a few thing you should ask yourself.
why userdetail is not camelCase?
why are you passing actions to connect method, when you aren't using it anywhere inside and when it can be used directly in the render?
Are you sure you really need to import everything from actions?
import { actionName } from '../actions'
Maybe something like this would be more beneficial if you are going to use something specific.
On another note, actions aren't used anywhere here, so I've removed them from my example.
why is google maps file named google_maps? Snake case should be only used for constants, for example in the case of google maps api key that will not change:
const GOOGLE_MAPS_API_KEY
Example:
import React from 'react';
import { connect } from 'react-redux';
import GoogleMap from 'google-map-react'
const UserDetail = (props) => {
const { latitude, longitude, email, address, countryCode } = props.userDetail;
const googleMapProps = {
bootstrapURLKeys: { key: "yourKey" },
center: [parseFloat(latitude), parseFloat(longitude)],
zoom: 12
};
const noDetails = <div>no data</div>;
const hasDetails = (
<div>
<GoogleMap {...googleMapProps}></GoogleMap>
<p>Email: {email}</p>
<p>Address: {address}</p>
<p>Latitude: {latitude}</p>
<p>Longitude: {longitude}</p>
<p>Country Code: {countryCode}</p>
</div>
);
return props.userDetail
? hasDetails
: noDetails;
}
function mapStateToProps(state){
const { userDetail } = state.auth;
return { userDetail };
}
export default connect(mapStateToProps)(UserDetail);

Related

Adding a 3rd Party Ad Script to a React App

I received an Ad Script that i need to include in my react app. The script tag runs in the body of the code and should load an image.
This is the tag im trying to insert.
<script type="text/adtag">
<ins class='dcmads' style='display:inline-block;width:300px;height:250px'
data-dcm-placement='N6246.289102DENTALPRODUCTSHOPPER/B27429766.334458108'
data-dcm-rendering-mode='script'
data-dcm-https-only
data-dcm-gdpr-applies='gdpr=${GDPR}'
data-dcm-gdpr-consent='gdpr_consent=${GDPR_CONSENT_755}'
data-dcm-addtl-consent='addtl_consent=${ADDTL_CONSENT}'
data-dcm-ltd='false'
data-dcm-resettable-device-id=''
data-dcm-app-id=''>
<script src='https://www.googletagservices.com/dcm/dcmads.js'></script>
</ins>
</script>
<script language="javascript" type="text/javascript" src="https://cdn.doubleverify.com/dvbs_src.js?ctx=2974662&cmp=27429766&plc=334458108&sid=7942714&dvregion=0&unit=300x250">
</script>
Ive tried creating a component that inserts the tag as a child of a div
function Script(props) {
const ref = useRef()
useEffect(() => {
if (ref.current) {
const fragment = document.createRange().createContextualFragment(`<div>${props.innerHTML}</div>`)
ref.current.appendChild(fragment)
}
}, [ref])
return <div ref={ref} />
}
And I've tried a few other things like using dangerouslysetinnerhtml but nothing seems to work.
If Successful the below image shows the code that should be inserted into the body.
expected result
Any help would be appreciated.

Setup Pinterest tag with Google Tag Manager doesn't work

I followed Pinterest steps to implement Pinterest tag on my Next.js website.
This is a no code implementation, I have Google Tag successfully installed on my website and I can see the events fired on the tag assistant.
However, the Pinterest tag isn't fired and I can't seem to find any exemple of React app with a Pinterest tag.
Because the previous method didn't work, I then tried the manual implementation but I don't think this this is the right code.
Manual implementation in _document.js :
<script
dangerouslySetInnerHTML={{ __html:`
!function(e){if(!window.pintrk){window.pintrk = function () {
window.pintrk.queue.push(Array.prototype.slice.call(arguments))};var
n=window.pintrk;n.queue=[],n.version="3.0";var
t=document.createElement("script");t.async=!0,t.src=e;var
r=document.getElementsByTagName("script")[0];
r.parentNode.insertBefore(t,r)}}("https://s.pinimg.com/ct/core.js");
pintrk('load', '<PINT_CODE>', {em: '<user_email_address>'});
pintrk('page');
` }}
/>
This is the solution I found:
<script
dangerouslySetInnerHTML={{ __html:`
!function(e){if(!window.pintrk){window.pintrk = function () {
window.pintrk.queue.push(Array.prototype.slice.call(arguments))};var
n=window.pintrk;n.queue=[],n.version="3.0";var
t=document.createElement("script");t.async=!0,t.src=e;var
r=document.getElementsByTagName("script")[0];
r.parentNode.insertBefore(t,r)}}("https://s.pinimg.com/ct/core.js");
pintrk('load', 'YOUR_CODE', {em: '<user_email_address>'});
pintrk('page');
` }}
/>

How to create a progress bar in Next.js?

I'm trying to create a Progress Bar which is at the very top of the website and each time you load the page, you see that Bar filling up.
I want to implement the same functionality in Next.js, but I'm struggling to do so. There are many libraries for the loading bar, but they all ask for a value prop which basically indicates how much the bar is filled, but I cannot find a way to get this value prop dynamically. I don't want to hardcode it, I want it to fill up as the page gets loaded.
Is there any way that I can find the value of the value prop dynamically?
There are a couple ways of doing that, nextjs have the Router import, so you can use the events see here
With that in mind you could create the visual component and if you really want to show on every page change, you could use this with your _app.tsx/jsx with the useEffect hook. Just don't forget to cleanup the events after listening to them
This answer does a great job showing it how to implement it, it's a great reference and very generic, so you can custom as much as you want
In __app.js or __app.tsx
import Router from 'next/router';
import NProgress from 'nprogress';
add the CSS for NProgress in the head:
<link rel="stylesheet" type="text/css" href="/nprogress.css" />
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());

How to refresh the facebook like url in reactjs (using facebook-sdk CDN)

I am using Facebook's like button as generated by facebook's like button configurator. However in order to get facebook-sdk to finish loading before the Like button, I had to use something called react-load-script and make a my own wrapper component for the like button html I got from the configurator.
my like button
class Like extends React.Component {
state = {
facebookLoaded: false
};
handleFacebookLoaded = () => this.setState({
facebookLoaded: true
});
FacebookSDK = () => <>
<div id="fb-root"></div>
<Script
async defer crossOrigin="anonymous"
url="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.3&appId=391623981325884&autoLogAppEvents=1"
onLoad={this.handleFacebookLoaded}
/>
</>;
render() {
return <>
<this.FacebookSDK />
{this.state.facebookLoaded
? <div class="fb-like" data-href={this.props.url} data-width="" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" />
: null}
</>;
}
}
In my code all the script loading stuff actually happens in App.jsx, but I moved it into one class just to show a simple version.
This part seems to work fine, the issue lies when changing the url passed to data-href.
I checked the react dom in the browser and the data-href is actually being updated properly, however this does not affect the actual url that is being used by the like button, unless I do a full page refresh. I'm assuming this has to do with how the data-href is being used by facebook-sdk. (edit: after testing I'm not sure anymore)
I've found many questions about this on Stack Overflow, however none of them seem to be based off the CDN version of facebook buttons
From what I understand, the div containing the href needs to be placed out and back into the DOM in order for the facebook-sdk to detect a change, but I don't know how to do this in react without a full page refresh. Also I'm not certain this is even the right solution.
-- Update --
I just noticed something else that seems like useful information. If I navigate to the page with the like button, then it doesn't show up. It will only show up if the page refreshes. I tested it by moving the part that loads the script into the like component (like in the example shown above) and that didn't change the behavior at all.
-- more experimenting --
I wrote an event handler that takes all the facebook related jsx out of the dom and back in (by toggling a button) However when all the code goes back into the dom (both jsx and html), the UI for the button does not come back. I'm really now sure how this is possible as I'm literally reloading the script and everything facebook related so this should be equivalent to a page refresh no?
I fixed the issue thanks to misorude. The part I was missing was calling window.FB.XFBML.parse(). I didn't realize I could access FB the same way using the CDN. If anyone is looking for a react solution here is the working code:
class Like extends React.Component {
constructor(props) {
super(props);
this.state = {
url: props.url,
}
}
handleChangePage() {
let likeBtn = document.createElement('div');
likeBtn.className = "fb-like";
likeBtn.setAttribute("data-href", this.props.url);
likeBtn.setAttribute("data-width", "");
likeBtn.setAttribute("data-layout", "button_count");
likeBtn.setAttribute("data-action", "like");
likeBtn.setAttribute("data-size", "large");
likeBtn.setAttribute("data-show-faces", "true");
likeBtn.setAttribute("data-share", "true");
let likePanel = document.getElementById("like-panel");
likePanel.removeChild(likePanel.childNodes[0]);
likePanel.appendChild(likeBtn);
window.FB.XFBML.parse(likePanel)
this.setState({ url: this.props.url });
}
componentDidMount() {
this.handleChangePage();
}
render() {
if(this.props.url !== this.state.url)
this.handleChangePage();
return <div id="like-panel">
{this.props.facebookLoaded
? <div className="fb-like" data-href={this.props.url} data-width="" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" />
: null}
</div>;
}
}
I moved the CDN out of this component so that it only loads the sdk once for the whole app.

How to create a redistributable widget using React

I want to build a widget using React that can be consumed by non-spa sites by pointing to a js file and adding a javascript snippet. E.g.
<script src="somepath/mycomponent.min.js"></script>
<script>MyComponent.render('id-of-a-div')</script>
I have created a component with React and setup webpack. I most spa-cases the top-level component ends with
ReactDOM.render(<MyComponent/>, document.getElementById(id));
My component won't be able to do this since it doesn't know to which element to render itself.
How and where should I create the function that would attach the component to an element?
you need a file with the methods that initialize and interacts with the parent page.
Maybe in utilities.js
export const utilities = {
// Here you will initialize the widget and you could pass an argument
// with the id of the tag where you wanna inject the app
initWidget: ( elementId ) => {
if( !elementId ){
document.createElement( 'rootApp' );
ReactDOM.render(<MyComponent/>, document.getElementById('rootApp'));
}
else {
ReactDOM.render(<MyComponent/>, document.getElementById(id));
}
},
}
And the utility will work in the tag of html to initilize it right there after all the js is loaded:
<script type='text/javascript' src='/widget.js'></script>
<script>
utilities.initWidget( 'myCustomId' );
</script>
Maybe a flow like this could be useful to you.

Resources