ErrorPro / react-google-autocomplete

React components for google places API.
MIT License
473 stars 114 forks source link

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

Open cmorbitzer opened 1 year ago

cmorbitzer commented 1 year ago

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

EduTel commented 4 months ago

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/>}
   <>
  )
}