'ant design onSelect is not firing
I'm trying to use Autocomplete from Ant Design, but the "onSelect" is not firing. Everything else is working well - when I type into the search bar, my ingredient list appears and filters as intended. If I console log "data" in onChange, the search's values appears (the "data"). When I click on an item from my filtered pop up menu, the menu disappears, the value in the input remains the same as before (i.e. it does not change to the selected item) and nothing is fired to the console. What am I doing wrong?
UPDATE: Added a sandbox.
Thanks in advance for your help.
export default function Searchbar() {
const [value, setValue] = useState('')
const [options, setOptions] = useState<{ value: string }[]>([]);
const ingredients = useSelector(state => state.ingredients);
const onSearch = (searchTerm: string) => {
setOptions(
!searchTerm ? [] : ingredients.filter(ferment =>
ferment.label.toLowerCase().includes(searchTerm.toLocaleLowerCase())
))
};
const onSelect = (data: string) => {
console.log("onSelect", data);
};
const onChange = (data: string) => {
setValue(data);
console.log(data)
};
return (
<>
<AutoComplete
options={options}
value={value}
style={{ width: 200 }}
onSelect={onSelect}
onSearch={onSearch}
onChange={onChange}
placeholder="looking for"
/>
</>
)
}
Solution 1:[1]
<AutoComplete />
expects prop options
with items that must have value
prop.
You pass ingredients
as options
to AutoComplete
and ingredients don't have this property.
This is the reason why the callback onSelect
is not firing.
Solution 2:[2]
When creating search options we need to specify value key :pair
for example value: item?.title,
for onSelect to understand which one was selected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yuri Dzabaev |
Solution 2 | Mohammed Shahed |