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

using react google autocomplete with react hook form?

Open kevinmachstudio opened this issue 3 years ago • 1 comments

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

kevinmachstudio avatar Aug 26 '22 18:08 kevinmachstudio

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

mcmxcdev avatar Sep 09 '22 06:09 mcmxcdev

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

AlexeyRDKV avatar Dec 09 '22 17:12 AlexeyRDKV