Skip to content

Latest commit

 

History

History
61 lines (44 loc) · 1.69 KB

useAutocomplete.md

File metadata and controls

61 lines (44 loc) · 1.69 KB

useAutocomplete Hook

React hook to use the Google Maps Places Autocomplete Widget in any component.

Usage

When initializing the <GoogleMapsProvider>, include the places library like this: libraries={['places']}.

import React, {useRef, useState} from 'react';
import {useAutocomplete} from '@ubilabs/google-maps-react-hooks';

const MyComponent = () => {
  const inputRef = useRef(null);
  const [inputValue, setInputValue] = useState('');

  const onPlaceChanged = place => {
    if (place) {
      setInputValue(place.formatted_address || place.name);
    }

    // Keep focus on input element
    inputRef.current && inputRef.current.focus();
  };

  useAutocomplete({
    inputField: inputRef && inputRef.current,
    onPlaceChanged
  });

  const handleInputChange = event => {
    setInputValue(event.target.value);
  };

  return (
    <input ref={inputRef} value={inputValue} onChange={handleInputChange} />
  );
};

Parameters

AutocompleteProps

Needs a reference to an Input field, some optional AutocompleteOptions and a callback for when a place got changed.

interface AutocompleteProps {
  inputField: HTMLInputElement | null;
  options?: google.maps.places.AutocompleteOptions;
  onPlaceChanged: (place: google.maps.places.PlaceResult) => void;
}

Return value

Returns an Autocomplete Places Widget instance to use directly.

google.maps.places.Autocomplete