npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@scragg0x/react-google-autocomplete

v3.2.1

Published

React component for google autocomplete.

Readme

GitHub license

The package provides 3 tools for working with google places services:

  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.

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. 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 <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 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.

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 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".

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 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

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 instance

More 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 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).

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.