Tintef / react-google-places-autocomplete

React Google Places Autocomplete input -- fully customizable
https://tintef.github.io/react-google-places-autocomplete
MIT License
376 stars 161 forks source link

Query & Show Suggestions on Focus #335

Open ahilke opened 1 year ago

ahilke commented 1 year ago

Problem

I want to show the menu with place suggestions already when the input is focussed, not just after the user typed something. I tried using defaultOptions: true as part of selectProps, which is almost what I want. However, it only works with the initial value and does not update the suggestions when the input is blurred and focussed again.

I am using the component as a controlled input, something like this:

const GooglePlacesAutocompleteContainer = () => {
  const [value, setValue] = useState('Paris');

  return (
    <GooglePlacesAutocomplete
      selectProps={{
        defaultOptions: true,
        inputValue: value,
        onInputChange: (newValue, meta) => {
          if (meta.action === 'input-change') {
            setValue(newValue);
          }
        },
      }}
    />
  );
};

The behaviour is as follows:

  1. Input mounts with value "Paris".
  2. On focus, suggestions for "Paris" are shown.
  3. Type "London", suggestions for "London" are shown.
  4. Blur the input - input value stays "London" and menu closes.
  5. Focus input again - suggestions for "Paris" are shown, but input value is "London". I would like to show suggestions for "London" instead.

I hope I didn't miss anything, but I tried quite a few combinations of props without any success.

Suggestions

I found this issue with a suggested solution in react-select, which pretty much describes my use case: https://github.com/JedWatson/react-select/issues/1525#issuecomment-744157380. However, I was not able to utilise this approach because I do not have access to the loadOptions function that is used by react-google-places-autocomplete. So an option could be to make this available as part of the library.

Alternatively, maybe there could be an option added to the GooglePlacesAutocomplete component, which would obviously more convenient.