How to integrate react-google-places-autocomplete with react-hook-from? - reactjs

I wanted to have a input for location in my form like below
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>

GooglePlacesAutocomplete uses react-select internally. In RHF docs, it shows you how to integrate with the Select component from react-select:
<Controller
name="iceCreamType"
control={control}
render={({ field }) => <Select
{...field}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
/>}
/>
GooglePlacesAutocomplete exposes a SelectProps prop to let you override the Select props, so this is how you use it with RHF:
const GooglePlacesAutocompleteComponent = ({ error, ...field }) => {
return (
<div>
<GooglePlacesAutocomplete
apiKey="xxxxxxxxxxxxxxx"
selectProps={{ ...field, isClearable: true }}
/>
{error && <div style={{ color: "red" }}>{error.message}</div>}
</div>
);
};
And in your form:
<Controller
name="location"
rules={{
required: "This is a required field"
}}
control={control}
render={({ field, fieldState }) => (
<GooglePlacesAutocompleteComponent
{...field}
error={fieldState.error}
/>
)}
/>

Related

How to reset MUI Autocomplete form on submit with React Hook Form?

How can I reset MUI Autocomplete form with React Hook Form on submit? Just reset() doesn't work with Autocomplete.
Codesandbox: https://codesandbox.io/s/custom-autocomplete-8dh17l?file=/src/App.tsx
export default function App() {
const {
handleSubmit,
control,
reset,
formState: { isDirty, isValid }
} = useForm<FormValues>({
mode: "onChange",
defaultValues: {
name: "",
dataset: []
}
});
const onSubmit = (data: any) => {
console.log("data:", data);
reset();
};
return (
<div>
<Stack onSubmit={handleSubmit(onSubmit)}>
<Controller
render={({ field: { onChange } }) => {
return (
<CustomAutocomplete
multiple
getOptionLabel={(option: Option) => option.name}
options={DATA}
label={"name"}
onChange={(e, options: Option[]) => onChange(options)}
/>
);
}}
name="dataset"
control={control}
rules={{
required: "Field is required"
}}
/>
<Button
type={"submit"}
disabled={!isDirty || !isValid}
>
Submit
</Button>
</Stack>
</div>
);
}
Try adding value to the CustomAutocomplete component. This passes the value to autocomplete field every time the value in controller gets updated
<Controller
render={({ field: { onChange, value } }) => {
return (
<CustomAutocomplete
multiple
getOptionLabel={(option: Option) => option.name}
options={DATA}
label={"name"}
value={value}
onChange={(e: FocusEvent, options: Option[]) =>
onChange(options)
}
/>
);
}}
name="dataset"
control={control}
rules={{
required: "Field is required"
}}
/>

react-google-autocomplete options not working

I am using react-google-autocomplete with react-hook-form:
And when I try to add options parameters to the Component (which should filter my API predictions down to my country, and only cities, but it's clearly not working:
const { register, handleSubmit , control} = useForm();
<Controller
name="location"
rules={{
required: "This is a required field"
}}
control={control}
render={({ field, fieldState }) => (
<PlaceAutoComplete
{...field}
error={fieldState.error}
/>
)}
/>
And the autocomplete component:
import GooglePlacesAutocomplete from "react-google-places-autocomplete";
export const PlaceAutoComplete = ({ error, ...field }) => {
return (
<div>
<GooglePlacesAutocomplete
apiKey="APIKEY"
apiOptions={{
types: ["(cities)"],
componentRestrictions: { country: "hu" },
}}
selectProps={{
...field,
isClearable: true,
}}
/>
{error && <div style={{ color: "red" }}>{error.message}</div>}
</div>
);
};
export default PlaceAutoComplete;
When I check the network log, you can see no options added to the query:
Request URL: https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictionsJson?1sLondon&4shu-HU&15e3&21m1&2e1&callback=_xdc_._dpoln7&key=APIKEY&token=111550
When I try to search for London, there should be no option, because I restrict to 'hu'- Hungary and only city:

React Hook form validation does not work on a controlled component

I'm fairly new to react hook form. I have a custom component made on top of material ui's autocomplete. The problem is that react hook form is not validating the field whatsoever. Here's how react hook form is setup
type FormData = {
eventTypes: string[];
};
const FORM_SCHEMA = yup
.object()
.shape({
eventTypes: yup.array().of(yup.string()).required('Please select event type(s)'),
})
.required();
const formInitialValues: FormData = {
eventTypes: [],
};
const {
handleSubmit,
formState: { errors },
register,
watch,
control,
} = useForm<FormData>({ resolver: yupResolver(FORM_SCHEMA), defaultValues: formInitialValues });
return (
<Controller
name="eventTypes"
control={control}
render={({ field, fieldState: { error } }) => (
<MultipleSelection
{...field}
items={['Avg. Door Time', 'Door Cycles', 'Mileage', 'Trips']}
label="Event Type(s)"
placeholder="Select event type(s)"
required
showAllTag
freeSolo={false}
error={!!error}
helperText={!!error?.message ?? ''}
color={error ? 'error' : 'default'}
/>
)}
/>
);
The onChange of the component works fine and on submitting the form gets the values. But the validation on the field that it shouldn't be an empty array and is required is not working.
Here's how multipleSelection looks like
<Autocomplete
ref={autoCompleteContainerRef}
multiple
disabled={disabled}
value={value}
classes={{
root: classes.root,
focused: classes.inFocus,
popupIndicator: classes.icon,
popper: classes.popper,
paper: classes.paper,
}}
className={classes.multipleSelect}
options={items}
size={size}
closeIcon={
<Icon
component={CloseIcon}
fontSize="small"
classes={{ root: classes.icon }}
/>
}
autoComplete
onChange={(event, newValue) => {
handleChange(newValue);
}}
getLimitTagsText={(more) => (
<Chip
classes={{ root: clsx(classes.chip, classes.more) }}
label={
<Typography noWrap variant="caption">
{`+${more} more`}
</Typography>
}
/>
)}
renderTags={handleRenderTags}
renderInput={(params) => (
<TextField
{...params}
{...textFieldProps}
placeholder={isEmpty(value) ? placeholder : ''}
className={classes.textField}
onKeyDown={onKeyDown}
/>
)}
renderOption={(option, state) => (
<StyledListItem
label={optionLabel(option)}
selected={state.selected}
classes={{ label: classes.label }}
/>
)}
{...rest}
/>
Does anyone have an idea why the validation is not working. Any help would be appreciated.
As it turns out, the culprit was this piece of code
const FORM_SCHEMA = yup
.object()
.shape({
eventTypes: yup.array().of(yup.string()).required('Please select event type(s)'), // <---
})
.required();
I changed it to the following
const FORM_SCHEMA = yup
.object()
.shape({
eventTypes: yup
.array()
.of(yup.string())
.test('empty-check', 'Please select event type(s)', value => value?.length !== 0),
})
.required();
And the validation works now.
I'm still not sure why it was not working in the first place. If anybody has a reasoning to why yup.array().of(yup.string()).required this was failing. Please let me know.

mui autocomplete with react-hook-form: defaultValue in formData

I'm setting the defaultValue of the Autocopmlete component as below:
<Controller
control={control}
name={name}
render={({field: {onChange, value}}) => (
<Autocomplete
freeSolo={freeSolo}
options={options}
renderInput={params => {
return <TextField {...params} label={label} margin="normal" variant="outlined" onChange={onChange} />
}}
onChange={(event, values, reason) => onChange(values)}
defaultValue={defaultValue}
/>
)}
/>
the value is well displayed based on the defaultValue.
However when I click on the submit button, the value of the Autocomplete field is always undefined if I don't use the autocomplete component.
Here are how I register the hook and component (simplified code)
const customerSchema = yup.object().shape({
route: yup.string().nullable()
})
const {control, handleSubmit} = useForm({
resolver: yupResolver(customerSchema)
})
const onSubmit = formData => {
console.log(formData) // autocomplete is undefined if no action on the autocomplete
}
<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
<AutoCompleteInput
control={control}
name="route"
label="route"
options={customers_routes.map(option => option.route_name)}
defaultValue={customer.route}
freeSolo={false}
/>
<Button type="submit">
Update
</Button>
</form>
What should I do to have the route field always available in the form data when I click on submit?
Why don't you use defaultValues option with useForm:
const {control, handleSubmit} = useForm({
resolver: yupResolver(customerSchema),
defaultValues: { route: customer.route },
});
and instead of sending defaultValue prop to AutoComplete you can use value prop, like this:
<Controller
control={control}
name={name}
render={({ field: { onChange, value } }) => (
<Autocomplete
freeSolo={freeSolo}
options={options}
renderInput={(params) => {
return (
<TextField
{...params}
label={label}
margin="normal"
variant="outlined"
onChange={onChange}
/>
);
}}
onChange={(event, values, reason) => onChange(values)}
value={value}
/>
)}
/>
Here is a simplest way to use an Autocomplete with react hook from , render your Autocomplete component inside Controller from react hook from, use onChange and value from the render function to control the value
<Controller
control={control}
name="type"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange, value } }) => (
<Autocomplete
freeSolo
options={['field', 'select', 'multiple', 'date']}
onChange={(event, values) => onChange(values)}
value={value}
renderInput={(params) => (
<TextField
{...params}
label="type"
variant="outlined"
onChange={onChange}
/>
)}
/>
)}

Proper way to use react-hook-form Controller with Material-UI Autocomplete

I am trying to use a custom Material-UI Autocomplete component and connect it to react-hook-form.
TLDR: Need to use MUI Autocomplete with react-hook-form Controller without defaultValue
My custom Autocomplete component takes an object with the structure {_id:'', name: ''} it displays the name and returns the _id when an option is selected. The Autocomplete works just fine.
<Autocomplete
options={options}
getOptionLabel={option => option.name}
getOptionSelected={(option, value) => option._id === value._id}
onChange={(event, newValue, reason) => {
handler(name, reason === 'clear' ? null : newValue._id);
}}
renderInput={params => <TextField {...params} {...inputProps} />}
/>
In order to make it work with react-hook-form I've set the setValues to be the handler for onChange in the Autocomplete and manually register the component in an useEffect as follows
useEffect(() => {
register({ name: "country1" });
},[]);
This works fine but I would like to not have the useEffect hook and just make use of the register somehow directly.
Next I tried to use the Controller component from react-hook-form to proper register the field in the form and not to use the useEffect hook
<Controller
name="country2"
as={
<Autocomplete
options={options}
getOptionLabel={option => option.name}
getOptionSelected={(option, value) => option._id === value._id}
onChange={(event, newValue, reason) =>
reason === "clear" ? null : newValue._id
}
renderInput={params => (
<TextField {...params} label="Country" />
)}
/>
}
control={control}
/>
I've changed the onChange in the Autocomplete component to return the value directly but it doesn't seem to work.
Using inputRef={register} on the <TextField/> would not cut it for me because I want to save the _id and not the name
HERE is a working sandbox with the two cases. The first with useEffect and setValue in the Autocomplete that works. The second my attempt in using Controller component
Any help is appreciated.
LE
After the comment from Bill with the working sandbox of MUI Autocomplete, I Managed to get a functional result
<Controller
name="country"
as={
<Autocomplete
options={options}
getOptionLabel={option => option.name}
getOptionSelected={(option, value) => option._id === value._id}
renderInput={params => <TextField {...params} label="Country" />}
/>
}
onChange={([, { _id }]) => _id}
control={control}
/>
The only problem is that I get an MUI Error in the console
Material-UI: A component is changing the uncontrolled value state of Autocomplete to be controlled.
I've tried to set an defaultValue for it but it still behaves like that. Also I would not want to set a default value from the options array due to the fact that these fields in the form are not required.
The updated sandbox HERE
Any help is still very much appreciated
The accepted answer (probably) works for the bugged version of Autocomplete. I think the bug was fixed some time after that, so that the solution can be slightly simplified.
This is very useful reference/codesandbox when working with react-hook-form and material-ui: https://codesandbox.io/s/react-hook-form-controller-601-j2df5?
From the above link, I modified the Autocomplete example:
import TextField from '#material-ui/core/TextField';
import Autocomplete from '#material-ui/lab/Autocomplete';
const ControlledAutocomplete = ({ options = [], renderInput, getOptionLabel, onChange: ignored, control, defaultValue, name, renderOption }) => {
return (
<Controller
render={({ onChange, ...props }) => (
<Autocomplete
options={options}
getOptionLabel={getOptionLabel}
renderOption={renderOption}
renderInput={renderInput}
onChange={(e, data) => onChange(data)}
{...props}
/>
)}
onChange={([, data]) => data}
defaultValue={defaultValue}
name={name}
control={control}
/>
);
}
With the usage:
<ControlledAutocomplete
control={control}
name="inputName"
options={[{ name: 'test' }]}
getOptionLabel={(option) => `Option: ${option.name}`}
renderInput={(params) => <TextField {...params} label="My label" margin="normal" />}
defaultValue={null}
/>
control is from the return value of useForm(}
Note that I'm passing null as defaultValue as in my case this input is not required. If you'll leave defaultValue you might get some errors from material-ui library.
UPDATE:
Per Steve question in the comments, this is how I'm rendering the input, so that it checks for errors:
renderInput={(params) => (
<TextField
{...params}
label="Field Label"
margin="normal"
error={errors[fieldName]}
/>
)}
Where errors is an object from react-hook-form's formMethods:
const { control, watch, errors, handleSubmit } = formMethods
So, I fixed this. But it revealed what I believe to be an error in Autocomplete.
First... specifically to your issue, you can eliminate the MUI Error by adding a defaultValue to the <Controller>. But that was only the beginning of another round or problems.
The problem is that functions for getOptionLabel, getOptionSelected, and onChange are sometimes passed the value (i.e. the _id in this case) and sometimes passed the option structure - as you would expect.
Here's the code I finally came up with:
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "#material-ui/core";
import { Autocomplete } from "#material-ui/lab";
import { Button } from "#material-ui/core";
export default function FormTwo({ options }) {
const { register, handleSubmit, control } = useForm();
const getOpObj = option => {
if (!option._id) option = options.find(op => op._id === option);
return option;
};
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<Controller
name="country"
as={
<Autocomplete
options={options}
getOptionLabel={option => getOpObj(option).name}
getOptionSelected={(option, value) => {
return option._id === getOpObj(value)._id;
}}
renderInput={params => <TextField {...params} label="Country" />}
/>
}
onChange={([, obj]) => getOpObj(obj)._id}
control={control}
defaultValue={options[0]}
/>
<Button type="submit">Submit</Button>
</form>
);
}
import { Button } from "#material-ui/core";
import Autocomplete from "#material-ui/core/Autocomplete";
import { red } from "#material-ui/core/colors";
import Container from "#material-ui/core/Container";
import CssBaseline from "#material-ui/core/CssBaseline";
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
import AdapterDateFns from "#material-ui/lab/AdapterDateFns";
import LocalizationProvider from "#material-ui/lab/LocalizationProvider";
import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
export default function App() {
const [itemList, setItemList] = useState([]);
// const classes = useStyles();
const {
control,
handleSubmit,
setValue,
formState: { errors }
} = useForm({
mode: "onChange",
defaultValues: { item: null }
});
const onSubmit = (formInputs) => {
console.log("formInputs", formInputs);
};
useEffect(() => {
setItemList([
{ id: 1, name: "item1" },
{ id: 2, name: "item2" }
]);
setValue("item", { id: 3, name: "item3" });
}, [setValue]);
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<Controller
control={control}
name="item"
rules={{ required: true }}
render={({ field: { onChange, value } }) => (
<Autocomplete
onChange={(event, item) => {
onChange(item);
}}
value={value}
options={itemList}
getOptionLabel={(item) => (item.name ? item.name : "")}
getOptionSelected={(option, value) =>
value === undefined || value === "" || option.id === value.id
}
renderInput={(params) => (
<TextField
{...params}
label="items"
margin="normal"
variant="outlined"
error={!!errors.item}
helperText={errors.item && "item required"}
required
/>
)}
/>
)}
/>
<button
onClick={() => {
setValue("item", { id: 1, name: "item1" });
}}
>
setValue
</button>
<Button
type="submit"
fullWidth
size="large"
variant="contained"
color="primary"
// className={classes.submit}
>
submit
</Button>
</form>
</Container>
</LocalizationProvider>
);
}
I do not know why the above answers did not work for me, here is the simplest code that worked for me, I used render function of Controller with onChange to change the value according to the selected one.
<Controller
control={control}
name="type"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange, value } }) => (
<Autocomplete
freeSolo
options={['field', 'select', 'multiple', 'date']}
onChange={(event, values) => onChange(values)}
value={value}
renderInput={(params) => (
<TextField
{...params}
label="type"
variant="outlined"
onChange={onChange}
/>
)}
/>
)}
Thanks to all the other answers, as of April 15 2022, I was able to figure out how to get this working and render the label in the TextField component:
const ControlledAutocomplete = ({
options,
name,
control,
defaultValue,
error,
rules,
helperText,
}) => (
<Controller
name={name}
control={control}
defaultValue={defaultValue}
rules={rules}
render={({ field }) => (
<Autocomplete
disablePortal
options={options}
getOptionLabel={(option) =>
option?.label ??
options.find(({ code }) => code === option)?.label ??
''
}
{...field}
renderInput={(params) => (
<TextField
{...params}
error={Boolean(error)}
helperText={helperText}
/>
)}
onChange={(_event, data) => field.onChange(data?.code ?? '')}
/>
)}
/>
);
ControlledAutocomplete.propTypes = {
options: PropTypes.arrayOf({
label: PropTypes.string,
code: PropTypes.string,
}),
name: PropTypes.string,
control: PropTypes.func,
defaultValue: PropTypes.string,
error: PropTypes.object,
rules: PropTypes.object,
helperText: PropTypes.string,
};
In my case, options is an array of {code: 'US', label: 'United States'} objects. The biggest difference is the getOptionLabel, which I guess needs to account for if both when you have the list open (and option is an object) and when the option is rendered in the TextField (when option is a string) as well as when nothing is selected.
I have made it work pretty well including multiple tags selector as follow bellow. It will work fine with mui5 and react-hook-form 7
import { useForm, Controller } from 'react-hook-form';
import Autocomplete from '#mui/material/Autocomplete';
//setup your form and control
<Controller
control={control}
name="yourFiledSubmitName"
rules={{
required: 'required field',
}}
render={({ field: { onChange } }) => (
<Autocomplete
multiple
options={yourDataArray}
getOptionLabel={(option) => option.label}
onChange={(event, item) => {
onChange(item);
}}
renderInput={(params) => (
<TextField {...params} label="Your label" placeholder="Your placeholder"
/>
)}
)}
/>
Instead of using controller, with the help of register, setValue of useForm and value, onChange of Autocomplete we can achieve the same result.
const [selectedCaste, setSelectedCaste] = useState([]);
const {register, errors, setValue} = useForm();
useEffect(() => {
register("caste");
}, [register]);
return (
<Autocomplete
multiple
options={casteList}
disableCloseOnSelect
value={selectedCaste}
onChange={(_, values) => {
setSelectedCaste([...values]);
setValue("caste", [...values]);
}}
getOptionLabel={(option) => option}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option}
</React.Fragment>
)}
style={{ width: "100%" }}
renderInput={(params) => (
<TextField
{...params}
id="caste"
error={!!errors.caste}
helperText={errors.caste?.message}
variant="outlined"
label="Select caste"
placeholder="Caste"
/>
)}
/>
);

Resources