google-map-react not loading- Uncaught TypeError: Cannot read properties of undefined (reading 'getChildren') - google-map-react

import React from "react";
import GoogleMapReact from "google-map-react";
const AnyReactComponent = ({ text }) => <div>{text}</div>;
export default function AppMapPage() {
const defaultProps = {
center: {
lat: 10.99835602,
lng: 77.01502627,
},
zoom: 11,
};
return (
<div style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "my key" }}
defaultCenter={defaultProps.center}
defaultZoom={defaultProps.zoom}
>
<AnyReactComponent lat={59.955413} lng={30.337844} text="My Marker" />
</GoogleMapReact>
</div>
);
}
I have been trying to solve it for a while. I am trying to run simple example of google-map-react. But, This does not load maps. Instead gives following errors and the page is blank.
google_map_markers.js:100 Uncaught TypeError: Cannot read properties of undefined (reading 'getChildren')
at o._getState (google_map_markers.js:100:1)
at new o (google_map_markers.js:248:1)
at constructClassInstance (react-dom.development.js:13522:1)
at updateClassComponent (react-dom.development.js:20497:1)
at beginWork (react-dom.development.js:22440:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
at invokeGuardedCallback (react-dom.development.js:4274:1)
at beginWork$1 (react-dom.development.js:27405:1)
at performUnitOfWork (react-dom.development.js:26513:1)

To resolve these issues, you have to remove *<React.StrictMode>* in the index.js file.
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>);
To
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

it's due to versioning. I downgraded from 18 to 17 and it worked. Man sometimes open source code consumes your all day.

I Just removed the <React.StrictMode> in the index.js file and it worked for me.

Related

How to access chrome.runtime from svelte project

I am building a svelte browser extension, and in order to load images, I found out that I can use chrome.runtime.getURL(relative_path), which is well supported across browsers.
So, I wrote this code:
<img
src={chrome.runtime.getURL("image.png")}
alt={"an image"}
/>
When trying to build, I get:
transforming (8) node_modules/.pnpm/svelte#3.55.1/node_modules/svelte/transition/ind13:09:26 [vite-plugin-svelte] /MyComponent.svelte:17:9 'chrome' is not defined
15: <button on:click={handleOnClick}>
16: <img
17: src={chrome.runtime.getURL("image.png")}
^
18: alt={"an image"}
19: />
✓ 25 modules transformed.
I tried to polyfill this using webextension-polyfill and #types/chrome npm packages with no success.
My workaround:
I created this function
const polifillImg = (img: string) => {
// At build time this will be replaced by chrome.runtime.getURL(imgSrcBase + img)
return (
"__REPLACE_WITH_CHROME__" + imgSrcBase + img + "__CLOSING_PARENTESIS__"
);
};
Which I can now use like so:
<img
src={polifillImg("image.png")}
alt={"an image"}
/>
And in my vite.config.ts:
import { defineConfig } from "vite";
import { svelte } from "#sveltejs/vite-plugin-svelte";
import { replaceCodePlugin } from "vite-plugin-replace";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
replaceCodePlugin({
replacements: [
{ from: '"__REPLACE_WITH_CHROME__" + ', to: "chrome.runtime.getURL(" },
{ from: ' + "__CLOSING_PARENTESIS__"', to: ")" },
],
}),
svelte(),
],
});
Which, you know, works, but it is not great.
I would like to know how to correctly use the chrome object the right way. Can someone show me the way?
Thanks

Getting type error while Implementing hereMap Api

I'm trying to add maps via hereMaps Api in my webApplication which is in Angular7 .While creating platform using service module which is
this.platform = new H.service.Platform({
"app_id": "{9qrlA6ZVcLPDw16Mkclk}",
});
I'm getting following saying ,
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'service' of undefined
TypeError: Cannot read property 'service' of undefined
i have installed npm here-js-api package and also declared service module
<script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
in src/index.html .but still i'm getting the same type error.!
Any solutions?
Add your script file to your angular.json in the script section
"scripts": [
...
"./node_modules/heremap/dist/heremap.min.js",
"./node_modules/heremap/dist/libhere.min.js",
]
Then styles in syle section
"styles": [
...
"./node_modules/heremap/css/heremap.css",
]
Now you have to declare Heremap from window and then use it:
declare const hm = window.heremap;
export class YourService {
// Now you can use hm
// eg.
hm.config({
app_id: APP_ID,
app_code: APP_CODE,
});
hm.getAvailableMapStyle().then(style => {
console.log("Style ", style);
});
// show map fragment
// to see console message, open debugger window
hm.map(
"map", {
zoom: 6,
scheme:"satellite.day",
viewChange: (zoom, coord) => {
console.log("viewchange", zoom, coord)
},
click: (coord, button, key) => {
console.log("click", coord, button, key)
},
keydown: (key) => {
console.log("key down", key)
}
}
);
}

React native: TypeError: null is not an object (evaluating 'SplashScreen.preventAutoHide')

My react native app was working just fine before I used expo eject. I ejected it because I now intend to build and release the app to the ios app store. As soon as I attempt to start the ejected app using react-native run-ios after it's been ejected I get the exception below.
Please could someone help to understand what's causing this issue and how to tackle it?
react Native versions as follows:
react-native-cli: 2.0.1
react-native: 0.61.5
TypeError: null is not an object (evaluating 'SplashScreen.preventAutoHide')
This error is located at:
in AppLoading (at AppLoading.js:52)
in AppLoading (at App.js:464)
in App (at renderApplication.js:40)
in RCTView (at AppContainer.js:101)
in RCTView (at AppContainer.js:119)
in AppContainer (at renderApplication.js:39)
preventAutoHide
SplashScreen.js:4:21
AppLoading#constructor
AppLoadingNativeWrapper.js:6:8
renderRoot
[native code]:0
runRootCallback
[native code]:0
renderApplication
renderApplication.js:52:52
runnables.appKey.run
AppRegistry.js:116:10
runApplication
AppRegistry.js:197:26
callFunctionReturnFlushedQueue
[native code]:0
The AppLoading component is not available in the bare workflow. As #gaurav-roy said you have to refactor your code.
Install the expo-splash-screen package with npm install expo-splash-screen
Add a splash-screen to your Android and iOS projects. Run npm run expo-splash-screen --help and follow the instructions of this CLI tool. (Because of a bug you might have to run the command again with the -p "ios" flag if it only adds the SplashScreen for Android after running it.
Change your code inside App.tsx in a similar way as in this example.
If you're working with hooks you probably want to add an useEffect
hook with an empty dependency list which runs an async function. Here an example of how it could be done:
const App = (props: Props) => {
const [isLoadingComplete, setLoadingComplete] = useState(false);
const init = async () => {
try {
// Keep on showing the SlashScreen
await SplashScreen.preventAutoHideAsync();
await loadResourcesAsync();
} catch (e) {
console.warn(e);
} finally {
setLoadingComplete(true);
// Hiding the SplashScreen
await SplashScreen.hideAsync();
}
useEffect(() => {
init();
}, []);
const renderApp = () => {
if (!isLoadingComplete && !props.skipLoadingScreen) {
return null;
}
return (
<Main />
);
};
return <StoreProvider>{renderApp()}</StoreProvider>;
}
As its evident from docs , SplashScreen is an inbuilt api for expo apps, and since you ejected it , it throws an error since it cant be used.
You can see this in the docs expo splashscreen .
First you should download npm i expo-splash-screen
And then change your import statement to :
import * as SplashScreen from 'expo-splash-screen';
Hope it helps. feel free for doubts
After looking through this SO page and then digging into some links, especially this expo page where they kind of provide a solution for this, I was able to get my app running after about 3 hours of struggle. They haven't added any functional component example, so I am sharing my code below in case someone came here looking for the solution.
import { Asset } from "expo-asset";
import * as Font from "expo-font";
import React, { useState, useEffect } from "react";
import { Platform, StatusBar, StyleSheet, View } from "react-native";
import { Ionicons } from "#expo/vector-icons";
import * as SplashScreen from 'expo-splash-screen';
import AppNavigator from "./navigation/AppNavigator";
export default props => {
const [isLoadingComplete, setLoadingComplete] = useState(false);
const theme = {
...DefaultTheme,
roundness: 2,
colors: {
...DefaultTheme.colors,
primary: "#E4002B",
accent: "#E4002B",
},
};
useEffect(() => {
async function asyncTasks() {
try {
await SplashScreen.preventAutoHideAsync();
} catch (e) {
console.warn(e);
}
await loadResourcesAsync()
setLoadingComplete(true);
}
asyncTasks()
}, []);
return (
!isLoadingComplete && !props.skipLoadingScreen ? null :
<View style={styles.container}>
{Platform.OS === "ios" && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
async function loadResourcesAsync() {
await Promise.all([
Asset.loadAsync([
require("./assets/images/logo.png") // Load your resources here (if any)
]),
Font.loadAsync({
// You can remove this if you are not loading any fonts
"space-mono": require("./assets/fonts/SpaceMono-Regular.ttf"),
}),
]);
await SplashScreen.hideAsync();
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
});
This solved it for me for an ejected expo app. Looks like expo was referencing it wrongly.
https://github.com/expo/expo/issues/7718#issuecomment-610508510
What worked for me was updating node_modules/expo/build/launch/splashScreen.js to the following as suggested by adamsolomon1986 in the repo (issue #7718):
import { NativeModules } from 'react-native';
import* as SplashScreen from 'expo-splash-screen'
export function preventAutoHide() {
if (SplashScreen.preventAutoHide) {
SplashScreen.preventAutoHide();
}
}
export function hide() {
if (SplashScreen.hide) {
SplashScreen.hide();
}
}
//# sourceMappingURL=SplashScreen.js.map

React Navigation get Param from deep linking not working

I have configured my router like:
const SwitchRouter = createSwitchNavigator(
{
Splash: {
screen: Launch,
path: 'hello/:code',
},
App: HomeStack,
},
{
initialRouteName: 'Splash',
}
);
I'm using a link in Safari, which launches my iOS app and then I should get a parameter from this link in my code.
I tried different with links but I was not able to get any parameter from them. Here is what I've tried:
myApp://hello/123
myApp://hello/?code=123
myApp://hello?code=123
My code which should get this code parementer is in my Launch screen as below:
const code = navigation.getParam('code', 'error');
The code value is always an error, my param here is never found.
Am I missing something here? I've been through all the GitHub and documentation of react-navigation I couldn't find a solution working for me.
I read some people have some issue getting their deep linking params in componentDidMount. Apparently they are not available.
So my code here in charge of getting my parameter 'code' I tried to use it inside componentDidMount/DidUpdate and even in the render but in all cases I can't get my param.
I figured that you cannot pass deeplink params to the first/initial screen.
You have to use a proxy instead:
const SwitchRouter = createSwitchNavigator(
{
CodeScreen: {
Screen: Code,
path: 'code/:code',
}
Splash: {
screen: Launch,
path: 'hello',
},
App: HomeStack,
},
{
initialRouteName: 'Splash',
}
});
class Code extends Component {
constructor(props) {
super(props);
const {navigation} = this.props;
const code = navigation.getParam('code', false);
navigation.navigate('hello', {code});
}
render() {
return (
<View>
</View>
);
}
}
Now you retrieve the 'code' param in your SplashScreen.

(React Native) Load local HTML file into WebView

I try to load the local .html file into WebView in React Native:
// load local .html file
const PolicyHTML = require('./Policy.html');
// PolicyHTML is just a number of `1`
console.log('PolicyHTML:', PolicyHTML);
// will cause an error: JSON value '1' of type NSNumber cannot be converted to NSString
<WebView html={PolicyHTML} />
The .html file should be read as a string, not as a resource representative.
How can I load the .html file into WebView in React Native?
By the way, what is the type of those resource representatives from require()? Is it number?
try it:
const PolicyHTML = require('./Policy.html');
<WebView
source={PolicyHTML}
style={{flex: 1}}
/>
I come across this post searching for loading static html.
If your html code is retrieved using, for example, an API, you can render WebView in this way:
<WebView
originWhitelist={['*']}
source={{ html: html, baseUrl: '' }}
/>
Notice that originWhitelistis required as explained in the documentation:
Note that static html will require setting of originWhitelist for
example to ["*"].
<View style={{flex: 1}}>
<WebView
style={{flex: 1}}
source={require("./resources/index.html")}
/>
</View>
To make WebView, the parent has to has a dimension or flex:1. We could set the WebView to flex: 1 too so that it fills up the parent.
If you need to serve local assets as well, then:
put all assets together with index.html into android/app/src/main/assets/www (You can copy them there with gradle task)
Then:
var uri = Platform.OS == "android" ?
"file:///android_asset/www/index.html" :
"./web/www/index.html"
return <WebView source={{ uri }} />
** For iOS didn't tested, please add instruction, how assets should be stored
With Expo tools and generally using Expo:
import { WebView } from "react-native-webview";
import { readAsStringAsync } from "expo-file-system";
import { useAssets } from "expo-asset";
export const MusicSheet = () => {
const [index, indexLoadingError] = useAssets(
require("../assets/musicsheetview/index.html")
);
const [html, setHtml] = useState("");
if (index) {
readAsStringAsync(index[0].localUri).then((data) => {
setHtml(data);
});
}
return (
<View style={styles.container}>
<WebView
onLoad={() => {}}
source={{ html }}
onMessage={(event) => {}}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
height: 100,
display: "flex",
},
});
Try this :
Add your .html file in your project.
Write such lines of code in the file where you want to use WebView Component
const OurStoryHTML = require ('./OurStory.html')
<WebView
source={OurStoryHTML}
style={{flex: 1, marginTop : 44}}
/>
It may help you.
If you're working with assets, project directories is different on the device's directory once the project is build and you can't simply reference them via string url.
Expo
If using expo, you have to require every asset then use useAssets on the require to cache them to the local storage of the device.
useAssets will return an object that contains a localUri
(this is the uri of the image that has been cached)
you can then use the localUri and put it as the src of the image
import { useAssets } from 'expo-asset';
/* . . . */
const IndexHTML = require('./assets/index.html');
const myImage = require('./assets/splash.png');
// url link after image is cached to the device
const [imgSrc, setImgSrc] = useState('');
const [image, imerr] = useAssets(myImage);
const [html, error] = useAssets(IndexHTML);
const webViewProps = {
javaScriptEnabled: true,
androidLayerType: 'hardware',
originWhitelist: ['*'],
allowFileAccess: true,
domStorageEnabled: true,
mixedContentMode: 'always',
allowUniversalAccessFromFileURLs: true,
onLoad: () => {
console.log(image[0].localUri);
setImgSrc(image[0].localUri);
},
source: {
html: '<img src="' + imgSrc + '"/>',
},
};
return <WebView {...webViewProps} />
const webViewProps = {
...
source: IndexHTML,
};
Note: for the expo apporach, files referenced in IndexHTML will not be found
The trick is to turn your html into a string literal to utilize template strings.
Then you have to manually require each of those assets to concatenate localUrl
require() has limited types supported and you need to add a metro.config.js in your root folder.
it will give errors if you require() a .js file since it reads it as a module rather, the workaround approach would be to bundle your assets
const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
config.resolver.assetExts.push(
// Adds support for asset file types
'css', 'ppt', 'obj'
);
module.exports = config;
Moreover, expo can hot reload changes done with the cached assets.
React Native
If you have the android folder in your directory, navigate to
android > app > build.gradle
then add
android {
/* link assets to the local storage of device */
sourceSets {
main { assets.srcDirs = ['src/main/assets', '../../source/assets/'] }
// [do not touch, 'relative to your asset'] }
}
. . .
finally, the relative folder you linked in gradle can be accessed through
file:///android_asset/
for ex. file:///android_asset/index.html -> /asset/index.html
return <WebView source={{uri: `file:///android_asset/index.html`}} />
For IOS, here's how
On the other hand, you have to rebuild vanilla react to see the changes in the assets.. which takes about 20 minutes or so
Alternative
A quick solution would be to integrate a static server, but this is a recent fork of the react-native-static-server that only works in vanilla react native.

Resources