Reputation: 8568
I am using React Antd v3 & upgrading it to v4, I noticed one issue, where the Autocomplete component was changed & now it is behaving in a weird manner
Passing a json array of [{value: string, label: 123}]
, everything works well except that on value selection, the value is shown (not the label)
How to show the label instead & keep the value selected as the option value?
Here is a link that shows the problem in a sandbox
Another link where passing array of Options also doesn't work correctly
Note:
It was working well in Ant v3, as shown in this link
Upvotes: 13
Views: 17464
Reputation: 161
You can use key
attribute to pass unique Id, and use value
as label. And then, use 2 parameters in your onSelect
function to retrieve the key or any other attributes.
The first parameter is used to pass the value, and
the second one is used to pass the object of the selected option.
Example data options:
const dataSource = [
{ key: 1, value: "John Doe"},
{ key: 2, value: "Jane Doe"}
]
Example field:
<AutoComplete
options={options}
onSelect={(val, option) => onSelect(val, option)}
onSearch={onSearch}
>
<Input.Search size="large" />
</AutoComplete>
Full code example: codesandbox
Upvotes: 16
Reputation: 8568
As indicated in the issue that I have opened on Antd repo, this behaviour is intended in the new version
However, the closest thing to what I needed is the Antd Select with a search option, which does exactly what was needed in my question without any hacks
Upvotes: 4
Reputation: 9671
According to the docs https://ant.design/components/auto-complete/#components-auto-complete-demo-basic
it's intented to use value when it's uncontrolled and passing options in. if you want the label to be different than the actual value, you have to use
const { Option } = AutoComplete;
and pass the array of Option into Autocomplete's Children
<AutoComplete style={{ width: 200 }} onSearch={handleSearch} placeholder="input here">
<Option value="111">Hello</Option>
</AutoComplete>
see https://ant.design/components/auto-complete/#components-auto-complete-demo-options
Upvotes: 3