I'm using React and I want to use a package which can only retrieved as an URL. In HTML it's easy to import using the script tag, but how to import to a JavaScript file?
What I want is to convert this
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
into something like this
import 'https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true'
Based on your comment when you import it directly in your html:
It throws an error which says that the objects of the script aren't
defined
I think the best approach here is to not try to import the js in another js file, but use the React google maps library instead, so you don't go through these hacks.
Try it and let us know.
The reason for this answer is that, even if you get the script working by adding another js file into your own js file, google maps api js will do more things that will give you trouble and issues in React (like the one you are having right now), and these issues have already been solved by this library.
Have a read at the official documentation to see if it works for you.
Example
There is a good tutorial and very basic example using this library here.
Example of using latitude and longitude (taken from this tutorial):
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
defaultZoom = { 13 }
>
</GoogleMap>
));
return(
<div>
<GoogleMapExample
containerElement={ <div style={{ height: `500px`, width: '500px' }} /> }
mapElement={ <div style={{ height: `100%` }} /> }
/>
</div>
);
Alternative library
Alternatively, you could use this library, as it is another react library for rendering google maps.
google-map-react
You can also follow this tutorial with this library.
These libraries have plenty of supporters and stars, meaning that you can always count on updates and helpful information.
Related
How do you load and use the google maps api using Nextjs?
1 - How do you load the api? I've tried to load it in _document.js:
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
const source = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&libraries=places`
const Document = () => {
return (
<Html>
<Head>
<Script type="text/javascript" src={source} strategy="beforeInteractive" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default Document
2 - How do you reference the API?
Something like: ? window.google.maps.places.AutocompleteService().getPlacePredictions()
But I get an error that google is undefined
I have also tried using npm libraries but none seem to work.
react-places-autocomplete
use-places-autocomplete
The Google Maps team provides a quick, helpful tutorial "How to load Maps JavaScript API in React" that uses the #react-google-maps/api package in a Next.js project. The code snippet below comes from the repo linked by the tutorial's author, #leighhalliday.
1. How to load the Google Maps JavaScript API
Pass your API key to useLoadScript
(a React hook provided by #react-google-maps/api that loads the Maps API)
Once loaded, return an instance of the GoogleMap component
In this simplified example, the initial location is memoized. But see the second example below for how you might use in conjunction with the Google Places API
You can optionally also add a Marker to the map
import { useMemo } from "react";
import { GoogleMap, useLoadScript, Marker } from "#react-google-maps/api";
export default function Home() {
const { isLoaded } = useLoadScript({
googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
});
if (!isLoaded) return <div>Loading...</div>;
return <Map />;
}
function Map() {
const center = useMemo(() => ({ lat: 44, lng: -80 }), []);
return (
<GoogleMap zoom={10} center={center} mapContainerClassName="map-container">
<Marker position={center} />
</GoogleMap>
);
}
2. How to add Autocomplete with the Places + Google Maps API's
The Google Maps team provide a second tutorial to implement search + autocomplete in your map that leverages the use-places-autocomplete package. You can also find the full code in #leighhalliday's repo example.
This is my first time making graphs in React so I'm following the guide and documentation. I have no prior experience with graphology, sigma.js or react-sigma (I know how to use normal React).
The setup documentation says:
Import the React Sigma style file in your application. Example : import "#react-sigma/core/lib/react-sigma.min.css"
What are style files? CSS? How can I make one? I can't find any documentation. Is it something basic from a previous library?
Honestly I'm finding it very hard to learn sigma.js and insert it in my react website. I can't find any guides. Are there any? I just want to start with a simple graph and learn from there.
The documentation refers specifically to their own CSS file which must be imported in a React app like they are showing in the example:
import "#react-sigma/core/lib/react-sigma.min.css";
Disclaimer: depending on your React app setup, the way to import a CSS file might differ.
The example in the documentation was broken when I wrote this answer. I opened an issue on the react-sigma repo and it was fixed since then.
When I tried it, some dependencies were missing and some changes were needed.
npm install #react-sigma/core sigma graphology graphology-types lodash
import { useEffect } from "react";
import Graph from "graphology";
import { SigmaContainer, useLoadGraph } from "#react-sigma/core";
// Import the style file here
import "#react-sigma/core/lib/react-sigma.min.css";
export const LoadGraph = () => {
// first change to their example
const loadGraph = useLoadGraph();
// also wrapped their graph instantiation side-effect with useEffect
useEffect(() => {
const graph = new Graph();
graph.addNode("first", {
// Required position
x: 1,
y: 1,
size: 15,
label: "My first node",
color: "#FA4F40"
});
// Calling the function that was missing from the example
loadGraph(graph);
}, [loadGraph]);
// Returning null to get a valid component
return null;
};
export const DisplayGraph = () => {
return (
<SigmaContainer style={{ height: "500px", width: "500px" }}>
<LoadGraph />
</SigmaContainer>
);
};
Note that I used TypeScript for the example, which gives insightful error messages since react-sigma provides its own types.
Then it was clear that the useLoadGraph hook wasn't used properly since it doesn't accept any parameter and it returns a function accepting a graph parameter. This can be confirmed with the API documentation.
I also figured that lodash was missing from errors in the developer console.
Please refer to the documentation as it's now up-to-date.
I am using react-gl library to use the map-api using mapbox. I have created an account mapbox as well still it is showing the error depicted in the picture.
Here is my code for app.js
import * as React from 'react';
import Map from 'react-map-gl';
function App() {
return (
<Map
initialViewState={{
longitude: -122.4,
latitude: 37.8,
zoom: 14
}}
mapboxApiAccessToken = {process.env.REACT_APP_MAPBOX}
style={{width: 600, height: 400}}
mapStyle="mapbox://styles/mapbox/streets-v9"
/>
);
}
export default App
Here is the error:
I faced the same problem. You must to change mapboxApiAccessToken to mapboxAccessToken.
Big shout out to Dani PĂ©rez. Apparently his answer is correct. Just to add on to his answer, in react-map-gl v7.0, they decided to rename various props and one of those props is mapboxApiAccessToken
Renamed props for better consistency with the wrapped library:
mapboxApiAccessToken is now mapboxAccessToken
This is mentioned in their Upgrade guide:
https://visgl.github.io/react-map-gl/docs/upgrade-guide
I am using a react pdf viewer and I would like to set up worker locally. I have tried doing that like this:
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
<Worker workerUrl={pdfjsWorker}>
<Viewer
fileUrl={url}
defaultScale={SpecialZoomLevel.PageFit}
plugins={[
defaultLayoutPluginInstance
]}
/>
</Worker>
But, that throws a warning:
Warning: Setting up fake worker
What is the correct way of import a worker then, why do I get this warning?
I was facing similar issues resolved them by adding the pdf.worker.js
Git Refrence
I added the js file in the head for the worker.js i.e https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.js
Then I correct the version (2.10.377 to 2.3.200) as per the console error and it starts loading the pdf
In my case, instead of write the code like this:
<script src="/js/pdf.worker.min.js"></script>
<script src="/js/pdf.min.js"></script>
I wrote it as:
<!--script src="/js/pdf.worker.min.js"></script--> // removed
<script src="/js/pdf.min.js"></script>
$(function() {
pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.min.js';
});
Which made the warning disappear ...
even though my PDF was rendered anyway - i just wanted that warning removed.
Watch out!
pdfjs version must be the same
Use it like below please
import { Worker, Viewer } from '#react-pdf-viewer/core';
import '#react-pdf-viewer/core/lib/styles/index.css';
import { pdfjs } from 'react-pdf';
const YourComponent = () => {
return (
<div>
<Worker workerUrl={`https://unpkg.com/pdfjs-dist#${pdfjs.version}/build/pdf.worker.min.js`}>
<Viewer fileUrl={fileUrl} />
</Worker>
</div>
)
};
Worker component expects a workerUrl which is of type string. You might have to replace pdfjsWorker in your code with actual pdf-worker url.
const pdfVersion = "2.6.347"
const pdfWorkerUrl = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfVersion}/pdf.worker.js`
<Worker workerUrl={pdfWorkerUrl}>
<Viewer
fileUrl={url}
defaultScale={SpecialZoomLevel.PageFit}
plugins={[
defaultLayoutPluginInstance
]}
/>
</Worker>
Note: Please make sure to set the same version for both pdfjs-dist and worker.
The official documentation mentions the same thing here: https://react-pdf-viewer.dev/docs/basic-usage/
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.0.279/pdf.worker.min.js'
Add this after you import pdfjs-dist and try matching the version(here 3.0.279) as per the console error. It worked for me.
I am developing a react native app. I am super confused that how to inject javascript code in react native. Though I am struggling somehow to work with react native but the thing is sometimes I need to inject some javascript code in my react native or say the homescreen.js type files, but I somehow end up into a syntax error. For example:
I am trying to implement this in a stylesheet.
const styles = Stylesheet.create({
//some styles
viewStyle:{
Platform.select({
ios:{
marginTop:2,
},
android:{
marginTop:3
}
});
}
//some styles
});
But it just does not work! it doesn't work even when I apply ...Platform instead of Platform.
**Note: I have import {Platform} from 'react-native'
My version is 0.57.something, but what I want to know is what is the syntax to implement javascript in these files. Just like for example in PHP we have the following:
<?php
//your logic
for(something){
?>
<View></View>
<?php
}
?>
Similarly for other languages we have something like the <% %>, {{ }} tags but what should I use in React Native. I always end up with a syntax error.
So my questions are, can anyone help me understand what the restriction is within React Native and where I can use and should not use tags? And if tags are available what are they?
I am super confused and was unable to find a similar question like this anywhere on Stack Overflow. I'd appreciate anyone's inputs, the more answers the more it will be helpful.
So I'm not sure what kind of structure you have set up but I'm going to assume you have a single file (lets call it homescreen.js) and you want to define styles for a component. I'm assuming you have already imported everything that's necessary (StyleSheet, Platform, View and Text from react-native, and the default export React from react).
So first, let's make the stylesheet. You almost have it correct above, you need the following:
const styles = Stylesheet.create({
viewStyle: Platform.select({
ios:{
marginTop:2,
},
android:{
marginTop:3
}
})
})
(You mention above that you're getting a syntax error, this is probably due to the semicolon in your stylesheet object.)
Now we need to create the React class for your HomeScreen component. Again, not sure of the context but you should be able to pull out the bits you need.
class HomeScreen extends React.Component {
render() {
return (
<View style={styles.viewStyle}>
<Text>I should have marginTop 2 on iOS and marginTop 3 on Android.</Text>
</View>
);
}
}