Search code examples
javascriptreactjsgoogle-places-apigoogle-places-autocomplete

How to load the Google Places JS API Library in a React Project?


I am using the 'react-places-autocomplete' library. I understand that I have to load the API using my key. I can't figure out where to place the script for the key such that the program will work.

I saw a StackOverflow page where someone said to load it statically in index.js, which I tried:

import 'react-places-autocomplete';
...
ReactDOM.render(
    <div>
    <BrowserRouter>
        <App />
    </BrowserRouter>
    <script src="https://maps.googleapis.com/maps/api/js? 
     key=MY_KEY&libraries=places"></script>
    </div>
    , document.getElementById('root'));

This doesn't work, I also tried to load it directly in the component (Which doesn't seem correct):

class My_Component extends React.Component {

...

render() {
    return (
        <div>
            <script src="https://maps.googleapis.com/maps/api/js? 
     key=MY_KEY&libraries=places"></script>
            <PlacesAutocomplete
                value={this.state.address}
                onChange={this.handleChange}
                onSelect={this.handleSelect}
            >

         ....

         </div>
        );
    }
}

Using these approaches I keep getting the "Google Maps JavaScript API library must be loaded" error, and I have looked at the documentation and it doesn't specify where the tag needs to be placed, just that it needs to be somewhere.


Solution

  • I have used it this way in one of my project

    class PlacesAutocomplete1 extends React.Component {
      constructor(props) {
      super(props);
      this.state = {
        googleMapsReady: false,
      };
    }
    
    componentDidMount() {
        script is loaded here and state is set to true after loading
        this.loadGoogleMaps(() => {
        // Work to do after the library loads.
        this.setState({ googleMapsReady: true });
      });
    }
    
    componentWillUnmount() {
      // unload script when needed to avoid multiple google scripts loaded warning
      this.unloadGoogleMaps();
    }
    
    loadGoogleMaps = callback => {
        const existingScript = document.getElementById("googlePlacesScript");
        if (!existingScript) {
            const script = document.createElement("script");
            script.src =
                "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places";
            script.id = "googleMaps";
            document.body.appendChild(script);
            //action to do after a script is loaded in our case setState
            script.onload = () => {
                if (callback) callback();
            };
        }
        if (existingScript && callback) callback();
    };
    
    unloadGoogleMaps = () => {
        let googlePlacesScript = document.getElementById("googlePlacesScript");
        if (googlePlacesScript) {
            googlePlacesScript.remove();
        }
    };
    
    render() {
        if (!this.state.googleMapsReady) {
            return <p>Loading</p>;
        }
        return (
            // do something you needed when script is loaded
    }