react-google-autocomplete

repository·master·Indexed 19 days ago

https://github.com/errorpro/react-google-autocomplete

A React library for integrating Google Places Autocomplete services. It provides the Autocomplete component for a ready-to-use input field, the usePlacesWidget hook for attaching autocomplete functionality to custom input elements via refs, and the usePlacesAutocompleteService hook for a debounced implementation of the Google Places Autocomplete service to manage API costs.

Tokens
3.1K
Snippets
11
Records
16
Agent score
66%

What's inside react-google-autocomplete

  1. Configure Google Maps API loading

    master

    You have two ways to load the Google Maps scripts required for the package to work:

    Pass the apiKey prop to the Autocomplete component or the usePlacesWidget hook. This will automatically load the necessary Google Maps scripts.

    Note: The Places API and Maps JavaScript API must both be enabled in your Google Cloud Console.

    2. Manual Loading

    If you do not provide an apiKey prop, you must manually include the Google Maps script in your application (e.g., in index.html).

    <script
      type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"
    ></script>
    <Autocomplete
      apiKey={YOUR_GOOGLE_MAPS_API_KEY}
      onPlaceSelected={(place) => console.log(place)}
    />
  2. Configure usePlacesAutocompleteService

    master

    The usePlacesAutocompleteService hook accepts a single config object with the following properties:

    • apiKey: Google API key (required unless Google Maps is loaded manually).
    • googleMapsScriptBaseUrl: Custom Google Maps 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.
    • sessionToken: If true, a session token will be attached to every request.
    • language: The language code for results.
    • libraries: Array of additional Google libraries to load (e.g., ['places']).
  3. Troubleshoot: Google Maps API loaded multiple times

    master
    If you encounter the error: You have included the Google Maps JavaScript API multiple times on this page, ensure you are not loading the Google Maps script manually in your HTML while also providing an apiKey to the library components, which triggers an automatic load.
  4. Access the Google Autocomplete instance

    master

    You can access the underlying Google Autocomplete instance through the onPlaceSelected callback or via the autocompleteRef returned by the usePlacesWidget hook.

    // Using the Autocomplete component
    <Autocomplete
      onPlaceSelected={(place, inputRef, autocomplete) => {
        console.log(autocomplete);
      }}
    />
    
    // Using the usePlacesWidget hook
    const { ref, autocompleteRef } = usePlacesWidget({
      apiKey: YOUR_GOOGLE_MAPS_API_KEY,
      onPlaceSelected: (place) => {
        console.log(place);
      },
    });
  5. Implement simple autocomplete with the Autocomplete component

    master

    Use the Autocomplete component for a quick, out-of-the-box implementation of Google Places autocomplete.

    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" },
      }}
      defaultValue="Amsterdam"
    />;
  6. Implement autocomplete using the usePlacesWidget hook

    master

    Use the usePlacesWidget hook to attach Google Autocomplete functionality to your own custom input element via a ref.

    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 <input ref={ref} style={{ width: "90%" }} defaultValue="Amsterdam" />;
    };
  7. usePlacesWidget Arguments and Return Values

    master

    Arguments

    usePlacesWidget accepts a single configuration object with the same properties as ReactGoogleAutocomplete props:

    • apiKey
    • ref
    • onPlaceSelected
    • onLoadFailed
    • options
    • inputAutocompleteValue
    • googleMapsScriptBaseUrl

    Returned Value

    The hook returns an object containing:

    • ref: A React ref to be assigned to your input element.
    • autocompleteRef: The autocomplete instance.
  8. Use the ReactGoogleAutocomplete component

    master

    The Autocomplete component is a simple HTML input component that provides the functionality of Google Places widgets. It can be used as a standalone input or customized via props.

    import Autocomplete from "react-google-autocomplete";
    
    <Autocomplete
      apiKey={YOUR_GOOGLE_MAPS_API_KEY}
      onPlaceSelected={(place) => {
        console.log(place);
      }}
    />;
  9. Use the usePlacesWidget hook

    master

    The usePlacesWidget hook provides the same functionality as the ReactGoogleAutocomplete component but does not create any DOM elements. Instead, it returns a ref that you can attach to any existing input element.

    import { usePlacesWidget } from "react-google-autocomplete";
    
    export default () => {
      const { ref, autocompleteRef } = usePlacesWidget({
        apiKey: YOUR_GOOGLE_MAPS_API_KEY,
        onPlaceSelected: (place) => {
          console.log(place);
        }
      });
    
      return <AnyInput ref={ref} />;
    }
  10. Use usePlacesAutocompleteService for debounced autocomplete

    master

    The usePlacesAutocompleteService hook provides a debounced implementation of the Google Places Autocomplete service. This is useful for reducing the number of requests sent to Google, which helps manage API costs.

    Note: This hook is not exported from the main index file. You must import it directly from react-google-autocomplete/lib/usePlacesAutocompleteService.

    import usePlacesService from "react-google-autocomplete/lib/usePlacesAutocompleteService";
    
    export default () => {
      const {
        placesService,
        placePredictions,
        getPlacePredictions,
        isPlacePredictionsLoading,
      } = usePlacesService({
        apiKey: process.env.REACT_APP_GOOGLE,
      });
    
      useEffect(() => {
        // fetch place details for the first element in placePredictions array
        if (placePredictions.length)
          placesService?.getDetails(
            {
              placeId: placePredictions[0].place_id,
            },
            (placeDetails) => savePlaceDetailsToState(placeDetails)
          );
      }, [placePredictions]);
    
      return (
        <>
          <Input
            placeholder="Debounce 500 ms"
            onChange={(evt) => {
              getPlacePredictions({ input: evt.target.value });
            }}
            loading={isPlacePredictionsLoading}
          />
          {placePredictions.map((item) => renderItem(item))}
        </>
      );
    };
  11. ReactGoogleAutocomplete Props Reference

    master

    The Autocomplete component accepts the following props:

    PropTypeDescription
    apiKeystringAutomatically loads Google maps scripts.
    refReactRefA React ref to be assigned to the underlying text input.
    onPlaceSelected(place: PlaceResult, inputRef: any, autocompleteRef: any) => voidInvoked when a user chooses a location. place is a PlaceResult.
    onLoadFailed(error: Error | ErrorEvent) => void(Optional) Invoked when the script fails to load or Google reports an auth/quota failure.
    optionsobjectGoogle autocomplete options. Includes types (default: ['cities']) and fields (default: ['address_components', 'geometry.location', 'place_id', 'formatted_address']).
    inputAutocompleteValuestringAutocomplete value to be set to the underlying input.
    googleMapsScriptBaseUrlstringCustom Google Maps URL. Default: https://maps.googleapis.com/maps/api/js
    defaultValuestringSets the default value for the input.
    languagestringSets the language for results.
    librariesstring[]Additional Google libraries to load. Default: ['places'].

    Note: You can also pass any standard HTML input tag props to this component.