// App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Map from "./Map.js"
class App extends React.Component {
constructor(props) {
super(props);
this.loadScript = this.loadScript.bind(this);
}
loadScript() {
const API_KEY = process.env.REACT_APP_API_KEY;
const url = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&libraries=places`;
const s = document.createElement("script");
s.src = url;
document.head.appendChild(s);
}
componentWillMount() {
this.loadScript();
}
render() {
return (
<div>
<Map />
</div>
);
}
}
export default App;
//Map.js
import React from "react"
export default class Map extends React.Component {
constructor(props) {
super(props);
this.loadMap = this.loadMap.bind(this);
}
loadMap() {
const map = new window.google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
componentWillMount() {
this.loadMap();
}
render() {
return (
<div id="map" style={{ width: 100, height: 100 }}></div>
);
}
}
Hi there, I am totally new to React, I am trying to load Google Maps without the help of a third-party library.
I have dynamically created a script tag and inserted it into the DOM. I am getting this error, trying to access the variables in the script.
My guess is that 'maps' is being accessed before the script is loaded. I am lost, on how to fix this error.