Ad

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.

  1. 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>
    

    enter image description here

  2. 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.

Ad

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>.

Ad
source: stackoverflow.com
Ad