React Google Autocomplete & Places Hooks
The `react-google-autocomplete` package provides flexible tools for integrating Google Places Autocomplete functionality into React applications. It offers a high-level `Autocomplete` component for quick setup, and lower-level hooks (`usePlacesWidget`, `usePlacesAutocompleteService`) for more control over UI and API interactions. The `usePlacesWidget` hook allows attaching autocomplete behavior to any input element via a ref, while `usePlacesAutocompleteService` provides direct programmatic access to the Google Places Autocomplete Service, including debounce functionality to optimize API requests. The current stable version is 2.7.5, with an active release cadence involving frequent minor and patch updates. Key differentiators include the dual approach of providing both a ready-to-use component and advanced hooks, built-in debounce, and comprehensive TypeScript types.
Common errors
-
Google Maps JavaScript API error: ApiNotActivatedMapError
cause The Google Maps JavaScript API is not enabled for the provided API key in your Google Cloud project.fixGo to Google Cloud Console, navigate to 'APIs & Services' -> 'Enabled APIs & services', and ensure 'Maps JavaScript API' is enabled for your project. -
Google Maps JavaScript API error: PlacesLibraryNotLoaded
cause The 'places' library, essential for autocomplete functionality, was not loaded with the Google Maps script.fixIf manually loading the script, ensure `&libraries=places` is included in the script URL (e.g., `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places`). If using the `apiKey` prop, ensure the 'Places API' is enabled in your Google Cloud Console. -
TypeError: Cannot read properties of undefined (reading 'lat')
cause Attempting to access `place.geometry.location.lat()` (or similar geometry properties) when the `geometry` field was not requested from the Google Places API.fixAdd `geometry` (or specific sub-fields like `geometry.location`) to the `options.fields` prop passed to the component or hook. For example: `options={{ fields: ["formatted_address", "geometry"] }}`. -
Autocomplete is not a function / Cannot destructure property 'usePlacesWidget' of ... as it is undefined.
cause Incorrect import statement. `Autocomplete` is a default export, while hooks like `usePlacesWidget` and `usePlacesAutocompleteService` are named exports.fixFor `Autocomplete`: `import Autocomplete from 'react-google-autocomplete';`. For hooks: `import { usePlacesWidget } from 'react-google-autocomplete';`.
Warnings
- breaking Version 2.1.0 introduced new hooks (`usePlacesWidget`, `usePlacesAutocompleteService`) that offer more control but represent a significant shift from the component-based approach for custom implementations. While the `Autocomplete` component remains, developers seeking granular control or custom UI will need to adapt to the new hook API.
- gotcha Correct Google Maps API Key and Library setup is crucial. The Google Cloud project associated with your API key must have both 'Maps JavaScript API' and 'Places API' enabled. Additionally, if manually loading the Google Maps script, the `&libraries=places` parameter is mandatory.
- gotcha Conflicting Google Maps Script Loading: The package can automatically load the Google Maps script if you provide the `apiKey` prop. However, if you also manually include the Google Maps script in your `index.html` or similar, this can lead to conflicts and unexpected behavior or errors.
- gotcha Incomplete Place Data (Missing Fields): By default, the Google Places API does not return all possible fields (e.g., `geometry`, `photos`, `address_components`). To access specific data like latitude/longitude, you must explicitly request these fields via the `options.fields` prop.
Install
-
npm install react-google-autocomplete -
yarn add react-google-autocomplete -
pnpm add react-google-autocomplete
Imports
- Autocomplete
import { Autocomplete } from 'react-google-autocomplete';import Autocomplete from 'react-google-autocomplete';
- usePlacesWidget
import usePlacesWidget from 'react-google-autocomplete';
import { usePlacesWidget } from 'react-google-autocomplete'; - usePlacesAutocompleteService
import usePlacesAutocompleteService from 'react-google-autocomplete';
import { usePlacesAutocompleteService } from 'react-google-autocomplete'; - Types for PlaceResult
import type { PlaceResult } from 'react-google-autocomplete';
Quickstart
import Autocomplete from "react-google-autocomplete";
import React from 'react';
function MyAutocompleteComponent() {
// Replace with your actual Google Maps API key or use environment variables
// Ensure GOOGLE_MAPS_API_KEY is defined in your environment or .env file
const YOUR_GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY ?? '';
if (!YOUR_GOOGLE_MAPS_API_KEY) {
console.error('GOOGLE_MAPS_API_KEY is not defined. Please provide your API key.');
return <div>API Key missing. Please set GOOGLE_MAPS_API_KEY.</div>;
}
return (
<div style={{ padding: '20px', maxWidth: '600px', margin: 'auto' }}>
<h1>Search for a Place</h1>
<p>Start typing an address or place name below:</p>
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place, inputRef, autocompleteRef) => {
console.log("Selected Place:", place);
if (place.geometry && place.geometry.location) {
console.log("Latitude:", place.geometry.location.lat());
console.log("Longitude:", place.geometry.location.lng());
}
console.log("Full Address:", place.formatted_address);
}}
options={{
types: ["(cities)"], // Example: restrict to cities
fields: ["address_components", "geometry", "icon", "name", "place_id", "formatted_address"]
}}
placeholder="Enter a city or location"
style={{
width: '100%',
padding: '10px',
fontSize: '16px',
border: '1px solid #ccc',
borderRadius: '4px'
}}
className="my-autocomplete-input"
/>
<p style={{ marginTop: '20px', fontSize: '0.9em', color: '#666' }}>
Ensure the Google Maps JavaScript API and Places API are enabled for your key.
</p>
</div>
);
}
export default MyAutocompleteComponent;