Receiving below error that initMap is not a function. I was trying not to use any extra packages to load this script asynchronously or for Google Maps API. I was trying to just console log initMap to see when the script is loaded, but I am still getting the error that it is not a function. I can move this function outside of componentDidMount or even outside of the App component, but the error is the same.
My guess is it has something to do with the fact that the script is getting loaded through document.createElement, but the initMap function is not, as when I look at other examples of Google Maps API it shows both the API URL and the initMap functoin on the index.html page.
Is this assumption correct? Is there a way to easily asynchronously load the function as a script or the Google Maps API in React without using any of the other packages?
Uncaught Ib {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new Ib (https://maps.googleapis.com/m…ZVRgF122wCkVf4P67Y&v=3.32&callback=initMap:163:56"}
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render( < App / > , document.getElementById('root'));
registerServiceWorker();
import React, {
Component
} from 'react'
import './App.css'
let map;
export default class App extends Component {
componentDidMount() {
function initMap() {
console.log('loaded')
}
const script = document.createElement('script')
script.async = true
script.defer = true
script.src = "https://maps.googleapis.com/maps/api/js?key={myAPIkey}=3.32&callback=initMap"
document.head.appendChild(script)
}
render() {
return ( <
div > {
this.map
} <
div style = {
{
width: 500,
height: 500
}
}
id = "map" / >
<
/div>
)
}
}
body {
font-family: Arial, sans-serif;
height: 100%;
margin: 0;
padding: 0;
}
#map {
width: 500;
height: 500;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>React Map</title>
</head>
<body>
<div id="root">
</div>
</body>
</html>