ErrorPro / react-google-autocomplete

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

using react google autocomplete with react hook form? #178

Closed kevinmachstudio closed 1 year ago

kevinmachstudio commented 2 years ago

Was hoping to integrate this with react hook form, is it possible? I'm getting this warning A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Second thing is when the user selects a choice from the google result dropdown list, I'm hoping the react hook form data will be automatically updated (e.g. the watch function would be triggered and the react hook form data would contain the selected result), although it's only being updated as the user types something, not selecting a result from the dropdown

 <Controller
    name="businessName"
    control={control}
    render={({
        field,
    }) => (
    <AutoComplete
        placeholder="Where to?"
        apiKey="GOOGLE_API_KEY"
        options={{
            types: ["establishment"],
            fields: ["name", "formatted_address"],
            }}
        {...field}
    />
    )}
/>
mcmxcdev commented 1 year ago

Pretty sure you need to change field to field: { ref: _ref, ...rest }. At least that is how we do this to avoid the warning.

AlexeyRDKV commented 1 year ago

Use setValue in onPlaceSelected function.

  const { handleSubmit, control, setValue } = useForm({
    defaultValues: {
      place: '',
    },
  });

 <Controller
     name="place"
     control={control}
     render={({ field }) => (
       <Autocomplete
           placeholder="Where to?"
           ref={inputRef}
           apiKey="GOOGLE_API_KEY"
           options={{
              types: ['establishment'],
              fields: ['name', 'formatted_address'],
            }}
           onPlaceSelected={selected => {
               setValue('place', selected.formatted_address);
             }}
           {...field}
          />
       )}
   />