Many web APIs can be used by adding the script tag to the head:
<html lang="en">
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
</head>
<body>
<div id="root" style="height: 100%"></div>
</body>
</html>
But when using libs like React and new features like ES6 this seems out of place. As in lets keep things modular -- the import should be close to the code that uses it.
How can we do the same, but in an ES6 file?
I was thinking of fetching it like this:
var request = require('request');
request('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places', function (error, response, body) {
if (!error && response.statusCode == 200) {
...
}
})
What should be done with what is returned? Append it to the head?
Update:
Error: ReferenceError: google is not defined
Am I loading the script at the wrong time?
const loadScript = (src) => {
const script = document.createElement("script")
script.type = "text/javascript"
script.src = src
document.getElementsByTagName("head")[0].appendChild(script)
}
class Geosuggest extends React.Component {
constructor(props) {
super(props)
loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places')
}
componentWillMount() {
this.autocompleteService = new google.maps.places.AutocompleteService();
}
}