React component for google autocomplete.
npm install @scragg0x/react-google-autocomplete




1. ReactGoogleAutocomplete is a component that renders a Google PlaceAutocompleteElement inside a container div.
2. usePlacesWidget is a react hook that provides the same functionality as ReactGoogleAutocomplete but gives you back a ref to a container div where the PlaceAutocompleteElement is mounted.
3. usePlacesAutocompleteService is a more complex react hook. It uses AutocompleteSuggestion.fetchAutocompleteSuggestions and provides all the functionality as the returned value. You can set a debounce prop 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 (Place class, PlaceAutocompleteElement, AutocompleteSuggestion). See Migration from previous versions for breaking changes.
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.
``js`
onPlaceSelected={(place) => console.log(place)}
/>
or
`js
const { ref } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => console.log(place),
});
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`html
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"
>
`ReactGoogleAutocomplete
This component renders a
container inside which a Google PlaceAutocompleteElement web component is mounted.`js
import Autocomplete from "react-google-autocomplete"; apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place) => {
console.log(place);
}}
/>;
`$3
-
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 element.-
onPlaceSelected: (place: Place, element: PlaceAutocompleteElement | null) => void: Invoked when a user selects a place. The place object 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: When true with bounds, restricts results to the given bounds.
- options.includedPrimaryTypes: New API name for types. Takes precedence if both provided.
- options.includedRegionCodes: New API name for componentRestrictions. Takes precedence if both provided.
- options.locationBias: New API name for bounds. Takes precedence if both provided.
- options.locationRestriction: Restrict results to bounds (new API).-
googleMapsScriptBaseUrl: Custom google maps script URL. Defaults to https://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 the PlaceAutocompleteElement.-
className: CSS class for the container .-
style: Inline styles for the container .-
id: HTML id for the container .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.`js
import { usePlacesWidget } from "react-google-autocomplete";export default () => {
const { ref, autocompleteRef } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
});
return
;
};
`$3
It has only one config argument with properties:
apiKey, ref, onPlaceSelected, options, googleMapsScriptBaseUrl, language, placeholder. See ReactGoogleAutocomplete props for details.$3
This hook returns an object with two properties:
-
ref - a react ref to assign to a container where the PlaceAutocompleteElement will 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.`js
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 (
<>
placeholder="Debounce 500 ms"
onChange={(evt) => {
getPlacePredictions({ input: evt.target.value });
}}
loading={isPlacePredictionsLoading}
/>
{placePredictions.map((item) => renderItem(item))}
>
);
};
`$3
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 to https://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 for includedPrimaryTypes. Mapped automatically.
- options.componentRestrictions: Legacy name for includedRegionCodes. Mapped automatically.
- options.bounds: Legacy name for locationBias. Mapped automatically.
- sessionToken: If true, a session token is attached to every request.
- language: Language code for results.
- libraries: Additional google libraries to load alongside places. Defaults to "places".$3
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 like placeId, text, mainText, secondaryText, and a toPlace() method.
- isPlacePredictionsLoading: true when a getPlacePredictions request is pending.
- getPlacePredictions: (opt: { input: string, ... }) => void: Call this to request place predictions. Accepts an object with input and any additional AutocompleteRequest properties.
- queryPredictions: An array of PlacePrediction objects (uses the same API as placePredictions).
- isQueryPredictionsLoading: true when a getQueryPredictions request is pending.
- getQueryPredictions: (opt: { input: string, ... }) => void: Call this to request query predictions. Uses the same fetchAutocompleteSuggestions API.Examples
$3
`js
import Autocomplete from "react-google-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:
`js
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:
`js
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
;
};
`$3
`js
const { ref, autocompleteRef } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
});
// autocompleteRef.current is the PlaceAutocompleteElement instance
`$3
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.`bash
cd examples
npm installSet your Google Maps API key
export VITE_GOOGLE_MAPS_API_KEY="your-api-key-here"npm run dev
`Then 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).$3
| 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 | RefObject (container) |
| ReactGoogleAutocomplete | Renders | Renders 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) |$3
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"] })` |- You have included the Google Maps JavaScript API multiple times on this page. Solution
If you would like to see something in this library please create an issue and I will implement it as soon as possible.