Search code examples
reactjsgoogle-places-apigoogle-places-autocomplete

Google places error in React 16 after upgrade from 15.x


I just upgraded my React app to React 16.0 from 15.x and now getting the following error. The code itself did not change other than the fact that it's now a React 16.0 app.

'google' is not defined no-undef

I use the auto complete feature in a util method I created as follows:

const map = new google.maps.Map(document.createElement('div'));
const googlePlacesAutocomplete = new google.maps.places.AutocompleteService();
const googlePlacesService = new google.maps.places.PlacesService(map);

export const googlePlacesAutoComplete = (keyword, callback) => {

    googlePlacesAutocomplete.getQueryPredictions({input: keyword}, (predictions, status) => {

        if(status !== google.maps.places.PlacesServiceStatus.OK) return callback(null);
        return callback(predictions);
    });
}

I simply point to Google Places libraries from the static HTML page for my React app's entry point.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=my-api-key"></script>

Any idea what's wrong? Any suggestions to fix this?


Solution

  • Have you tried ’window.google’? ’google’ is global and it is recommend not to use globals as is.

    Also, if you can, try to add ’google’ as a module to ensure it as veen loaded before use. And possibly avoid a global variable or anything could override its value.