Home > other >  How to integrate react-google-places-autocomplete with react-hook-from?
How to integrate react-google-places-autocomplete with react-hook-from?

Time:10-22

I wanted to have a input for location in my form like below

enter image description here

I am using a ready made component for this https://www.npmjs.com/package/react-google-places-autocomplete

import React from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";

const GooglePlacesAutocompleteComponent = () => (
  <div>
    <GooglePlacesAutocomplete
      apiKey="xxxxxxxxxxxxxxx"
    />
  </div>
);

export default Component;

What I generally do the following with react hook form for with a material ui Textfield is:

const validationSchema = Yup.object().shape({
  location: Yup.string().required("Location is required"),
});

const {
  control,
  handleSubmit,
  formState: { errors },
  reset,
  setError,
} = useForm({
  resolver: yupResolver(validationSchema),
});

and materialui textfield

<Controller
  name="location"
  control={control}
  render={({ field: { ref, ...field } }) => (
    <TextField
      {...field}
      inputRef={ref}
      fullWidth
      label="location"
      margin="dense"
      error={errors.location ? true : false}
    />
  )}
/>
<Typography variant="inherit" color="textSecondary">
  {errors.name?.message}
</Typography>

So Here instead of TextField I have to use GooglePlacesAutocompleteComponent

I want user to know its required.

I think something like below should be possible, but I am not getting what props to pass:

<Controller
  name="location"
  control={control}
  render={({ field: { ref, ...field } }) => (
    <GooglePlacesAutocompleteComponent
      <--------------------------->
      But for this component how can i pass the below things
      {...field}
      inputRef={ref}
      fullWidth
      label="location"
      margin="dense"
      error={errors.location ? true : false}
      <--------------------------->
    />
  )}
/>
<Typography variant="inherit" color="textSecondary">
  {errors.name?.message}
</Typography>

CodePudding user response:

GooglePlacesAutocomplete uses Codesandbox Demo

  • Related