react-google-autocomplete icon indicating copy to clipboard operation
react-google-autocomplete copied to clipboard

usePlacesWidget does not work if input ref does not exist on mount

Open cmorbitzer opened this issue 3 years ago • 1 comments

usePlacesWidget() doe not work if the input element does not exist on mount.

This does not work (simplified example):

const { ref } = usePlacesWidget({
    apiKey: XXX,
    options: {
      region: 'us',
      types: ['address'],
    },
    onPlaceSelected: (place) => {},
  });

const [isInputShown, setIsInputShown] = useState(false);

return (
    <div>
        <button onClick={() => setIsInputShown(true)}>Show input</button>
        {isInputShown && <input ref={ref} />}
    </div>
);

because of this line: https://github.com/ErrorPro/react-google-autocomplete/blob/214a7c3d4740d2bfcf85264717b0e0da5bd0b333/src/usePlacesWidget.js#L52

which is in a useEffect hook that only runs on mount.

Because of the rules of hooks, I am not able to imperatively instantiate the places widget either using usePlacesWidget.

Related to #170

cmorbitzer avatar Sep 22 '22 19:09 cmorbitzer

you could create another component

const AutocompleteLoaded = () => {
  const { ref } = usePlacesWidget(
    {
      apiKey: YOUR_GOOGLE_MAPS_API_KEY,
      onPlaceSelected: (place) => {
        console.log(place);
      },
      options: options,
    }
  );
  return (
    <TextField
      fullWidth
      label="Address"
      variant="outlined"
      inputRef={ref} // Attach the Google places autocomplete hook
    />
  );
};

const App = ()=>{
   const [isInputShown, setIsInputShown] = useState(false);

  return (
  <>
        <button onClick={() => setIsInputShown(true)}>Show input</button>
        {isInputShown && <AutocompleteLoaded/>}
   <>
  )
}

EduTel avatar May 05 '24 01:05 EduTel