Load Google Place API In Gatsbyjs (Reactjs) Project
I am trying to use the AutoComplete address service from Google Place API.
Found this library: https://github.com/kenny-hibino/react-places-autocomplete#load-google-library
It asks for loading the library in my project: https://github.com/kenny-hibino/react-places-autocomplete#getting-started
I would do it in the public/index.html if it's pure Reactjs project. However, the public/index.html in Gatsbyjs project will be deleted and re-generated every time when running:
Gatsby develop
command line.
How can I use the Google Place API in my Gatsbyjs project?
Update
I have tried 2 ways to achieve this.
Use React-Helmet in /layouts/index.js , here is how it looks like:
<Helmet> <script src="https://maps.googleapis.com/maps/api/js?key={API}&libraries=places&callback=initAutocomplete" async defer></script> </Helmet>
Put the script reference in the /public/index.html, which looks like this:
<!DOCTYPE html> <html> <head> <meta charSet="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <title data-react-helmet="true"></title> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={API_KEY}&libraries=places" async defer ></script> </head> <body> <div id="___gatsby"></div> <script src="/commons.js"></script> </body> </html>
For the 1st solution, every time after I refresh my page, the project throws an error asking for loading the Google JavaScript Map API.
For the 2nd solution, every time after I re-start the Gatsby by the command line: gatsby develop
it re-generates the index.html which flushes away my JavaScript reference in it.
Answer
You shouldn't modify any files in the public
forlder with GatsbyJS.
Instead, I recommend you to customize your html.js
file.
To do so, first run:
cp .cache/default-html.js src/html.js
You should have the html.js
file in /src/html.js.
Now you can put your <script>
tag within the <head>
.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?