@scragg0x/react-google-autocomplete
v3.2.1
Published
React component for google autocomplete.
Maintainers
Keywords
Readme

The package provides 3 tools for working with google places services:
- ReactGoogleAutocomplete is a component that renders a Google PlaceAutocompleteElement inside a container div.
- usePlacesWidget is a react hook that provides the same functionality as
ReactGoogleAutocompletebut gives you back a ref to a container div where thePlaceAutocompleteElementis mounted. - usePlacesAutocompleteService is a more complex react hook. It uses AutocompleteSuggestion.fetchAutocompleteSuggestions and provides all the functionality as the returned value. You can set a
debounceprop to reduce the number of requests sent to Google.
If you find this package helpful please give it a star because it helps it grow and motivates us to build new features and support the old ones.
Note: This version uses the new Google Places API (
Placeclass,PlaceAutocompleteElement,AutocompleteSuggestion). See Migration from previous versions for breaking changes.
Install
npm i react-google-autocomplete --save
or
yarn add react-google-autocomplete
You can pass an apiKey prop to automatically load the Google Maps scripts. The api key can be found in your google cloud console. The Places API (New) and Maps JavaScript API must be enabled.
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place) => console.log(place)}
/>or
const { ref } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => console.log(place),
});
<div ref={ref} />Alternatively if not passing the apiKey prop, you can include google maps script in your app. Somewhere in index.html or somewhere else. More info here
<script
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"
></script>ReactGoogleAutocomplete
This component renders a <div> container inside which a Google PlaceAutocompleteElement web component is mounted.
import Autocomplete from "react-google-autocomplete";
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place) => {
console.log(place);
}}
/>;Props
apiKey: Pass to automatically load the Google maps scripts. The api key can be found in your google cloud console.ref: React ref assigned to the container<div>element.onPlaceSelected: (place:Place, element:PlaceAutocompleteElement| null) => void: Invoked when a user selects a place. Theplaceobject has camelCase fields (e.g.formattedAddress,addressComponents).options: Configuration options for the autocomplete element.options.types: Array of place types to filter results. Legacy shorthands like(cities)and(regions)are mapped automatically.options.fields: Fields to fetch when a place is selected. Legacy snake_case names (e.g.address_components,geometry.location,place_id) are mapped to new camelCase names automatically. Defaults to["address_components", "geometry.location", "place_id", "formatted_address"].options.componentRestrictions: Restrict results to specific countries, e.g.{ country: "us" }.options.bounds: Bias results to a given area.options.strictBounds: Whentruewithbounds, restricts results to the given bounds.options.includedPrimaryTypes: New API name fortypes. Takes precedence if both provided.options.includedRegionCodes: New API name forcomponentRestrictions. Takes precedence if both provided.options.locationBias: New API name forbounds. Takes precedence if both provided.options.locationRestriction: Restrict results to bounds (new API).
googleMapsScriptBaseUrl: Custom google maps script URL. Defaults tohttps://maps.googleapis.com/maps/api/js.language: Set language for results.libraries: Additional google libraries to load alongside places. Defaults to"places".placeholder: Placeholder text forwarded to thePlaceAutocompleteElement.className: CSS class for the container<div>.style: Inline styles for the container<div>.id: HTML id for the container<div>.
usePlacesWidget
Is a hook that has a single config argument. It has the same interface as ReactGoogleAutocomplete props (except className, style, id). This hook is used internally by the ReactGoogleAutocomplete component.
import { usePlacesWidget } from "react-google-autocomplete";
export default () => {
const { ref, autocompleteRef } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
});
return <div ref={ref} />;
};Arguments
It has only one config argument with properties: apiKey, ref, onPlaceSelected, options, googleMapsScriptBaseUrl, language, placeholder. See ReactGoogleAutocomplete props for details.
Returned value
This hook returns an object with two properties:
ref- a react ref to assign to a container<div>where thePlaceAutocompleteElementwill be mounted.autocompleteRef- a ref to the PlaceAutocompleteElement instance.
usePlacesAutocompleteService
This hook provides a debounced interface to the Google Places autocomplete suggestions API. It uses AutocompleteSuggestion.fetchAutocompleteSuggestions and reduces request volume via lodash.debounce.
import { usePlacesAutocompleteService } from "react-google-autocomplete";
export default () => {
const {
placePredictions,
getPlacePredictions,
isPlacePredictionsLoading,
} = usePlacesAutocompleteService({
apiKey: process.env.REACT_APP_GOOGLE,
});
useEffect(() => {
// fetch full place details for the first prediction
if (placePredictions.length) {
const place = placePredictions[0].toPlace();
place.fetchFields({ fields: ["formattedAddress", "location"] })
.then(({ place }) => savePlaceDetailsToState(place));
}
}, [placePredictions]);
return (
<>
<Input
placeholder="Debounce 500 ms"
onChange={(evt) => {
getPlacePredictions({ input: evt.target.value });
}}
loading={isPlacePredictionsLoading}
/>
{placePredictions.map((item) => renderItem(item))}
</>
);
};Arguments
The hook has only one config argument.
config:apiKey: Google api key, otherwise the Google API must be loaded manually.googleMapsScriptBaseUrl: Custom google maps script URL. Defaults tohttps://maps.googleapis.com/maps/api/js.debounce: Number of milliseconds to accumulate responses for.options: Default options passed to every request.options.input: Default input text.options.includedPrimaryTypes: Array of place types to filter results.options.includedRegionCodes: Array of CLDR region codes to restrict results.options.locationBias: Bias results to a location.options.locationRestriction: Restrict results to bounds.options.types: Legacy name forincludedPrimaryTypes. Mapped automatically.options.componentRestrictions: Legacy name forincludedRegionCodes. Mapped automatically.options.bounds: Legacy name forlocationBias. Mapped automatically.
sessionToken: Iftrue, a session token is attached to every request.language: Language code for results.libraries: Additional google libraries to load alongside places. Defaults to"places".
Returned value
The hook returns an object with properties:
autocompleteSessionToken: Instance of AutocompleteSessionToken. You can use this to group several requests into a single session.refreshSessionToken: Call this function to refresh the session token.placePredictions: An array of PlacePrediction objects. Each has properties likeplaceId,text,mainText,secondaryText, and atoPlace()method.isPlacePredictionsLoading:truewhen agetPlacePredictionsrequest is pending.getPlacePredictions: (opt: { input: string, ... }) => void: Call this to request place predictions. Accepts an object withinputand any additional AutocompleteRequest properties.queryPredictions: An array of PlacePrediction objects (uses the same API asplacePredictions).isQueryPredictionsLoading:truewhen agetQueryPredictionsrequest is pending.getQueryPredictions: (opt: { input: string, ... }) => void: Call this to request query predictions. Uses the samefetchAutocompleteSuggestionsAPI.
Examples
Simple autocomplete with options
import Autocomplete from "react-google-autocomplete";
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
style={{ width: "90%" }}
onPlaceSelected={(place) => {
console.log(place);
}}
options={{
types: ["(regions)"],
componentRestrictions: { country: "ru" },
}}
/>;or using the new option names:
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
style={{ width: "90%" }}
onPlaceSelected={(place) => {
console.log(place.formattedAddress);
}}
options={{
includedPrimaryTypes: ["locality", "sublocality", "postal_code", "country",
"administrative_area_level_1", "administrative_area_level_2"],
includedRegionCodes: ["ru"],
}}
/>;or with the hook:
import { usePlacesWidget } from "react-google-autocomplete";
export default () => {
const { ref } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
options: {
types: ["(regions)"],
componentRestrictions: { country: "ru" },
},
});
return <div ref={ref} style={{ width: "90%" }} />;
};Getting access to the PlaceAutocompleteElement instance
const { ref, autocompleteRef } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
});
// autocompleteRef.current is the PlaceAutocompleteElement instanceMore examples
Code snippets: docs/examples.js, docs/debounce.js, docs/formik.js
Running the example app
A runnable Vite + React example app lives in examples/. It includes basic usage, hook usage, Mantine integration, and debounced service hook demos.
cd examples
npm install
# Set your Google Maps API key
export VITE_GOOGLE_MAPS_API_KEY="your-api-key-here"
npm run devThen open the URL shown in the terminal (usually http://localhost:5173).
Your API key must have the Places API (New) and Maps JavaScript API enabled in the Google Cloud Console.
Migration from previous versions
This version migrates from the legacy Google Places API (Autocomplete, AutocompleteService, PlacesService) to the new Places API (PlaceAutocompleteElement, AutocompleteSuggestion, Place class).
Breaking changes
| What changed | Old | New |
|---|---|---|
| onPlaceSelected 1st arg | PlaceResult (snake_case fields like formatted_address) | Place (camelCase fields like formattedAddress) |
| onPlaceSelected 2nd arg | HTMLInputElement | PlaceAutocompleteElement |
| onPlaceSelected 3rd arg | Autocomplete instance | Removed |
| usePlacesWidget ref type | RefObject<HTMLInputElement> | RefObject<HTMLDivElement> (container) |
| ReactGoogleAutocomplete | Renders <input> | Renders <div> containing PlaceAutocompleteElement |
| ReactGoogleAutocomplete props | All InputHTMLAttributes | Only className, style, id, placeholder |
| inputAutocompleteValue prop | Supported | Removed (not applicable) |
| defaultValue prop | Supported | Removed (not applicable) |
| Service hook return | Includes placesService, placesAutocompleteService | Removed (use Place class directly) |
| Prediction type | AutocompletePrediction | PlacePrediction |
| Query predictions type | QueryAutocompletePrediction | PlacePrediction (same type) |
Backward compatible options
Legacy option names are still accepted and mapped internally:
| Legacy option | Maps to |
|---|---|
| types: ["(cities)"] | includedPrimaryTypes: ["locality", "administrative_area_level_3"] |
| types: ["(regions)"] | includedPrimaryTypes: ["locality", "sublocality", "postal_code", ...] |
| componentRestrictions: { country: "us" } | includedRegionCodes: ["us"] |
| bounds | locationBias |
| fields: ["formatted_address"] | fetchFields({ fields: ["formattedAddress"] }) |
Troubleshooting
- You have included the Google Maps JavaScript API multiple times on this page. Solution
Contribution
If you would like to see something in this library please create an issue and I will implement it as soon as possible.
