Load Google Place API In Gatsbyjs (Reactjs) Project

I am trying to use the AutoComplete address service from Google Place API.

Found this library:

It asks for loading the library in my project:

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?


I have tried 2 ways to achieve this.

  1. Use React-Helmet in /layouts/index.js , here is how it looks like:

          <script src="{API}&libraries=places&callback=initAutocomplete" async defer></script>

    enter image description here

  2. Put the script reference in the /public/index.html, which looks like this:

    <!DOCTYPE html>
        <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="/"></script>
        <script type="text/javascript" src="{API_KEY}&libraries=places" async defer ></script>
        <div id="___gatsby"></div>
        <script src="/commons.js"></script>

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.



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