I'm using ant design AutoComplete
for a location selection. And the data source is an array. Here is my code.
<Form.Item
label={t("City")}
name="location"
rules={[
{
required: true,
message: t("Please enter your city"),
},
]}
>
<AutoComplete
options={this.props.cityList}
allowClear={true}
placeholder={t("Enter your city")}
className="ant-select-custom"
filterOption={(inputValue, option) =>
option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
}
/>
</Form.Item>
The problem is, I can type anything that not in the data source. What I want it to restrict that. If I type something that not in the data source, The value should be erased. I tried with onBlur()
and onChange()
but no luck. Can anyone help me with this?
Thanks in advance
set value props in AutoComplete tag, and set an state for it, check if value on search is not found change the state to the initial.
const [value, setValue] = useState('');
const handleSearch = async val => {
if (val) {
const response = await dispatch(yourAction(val));
if (!response?.length) {
...
setValue(''); // this will clear the input
} else {
...
}
} else {
...
}
};
<AutoComplete
...,
value={value}
/>
This works for me.