Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Antd v4 autocomplete shows selected value instead of label upon selecting an option

Tags:

reactjs

antd

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

like image 282
Ahmed Elkoussy Avatar asked Mar 04 '20 16:03

Ahmed Elkoussy


2 Answers

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

like image 55
sepwulanarie Avatar answered Sep 21 '22 08:09

sepwulanarie


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

like image 23
Yichaoz Avatar answered Sep 20 '22 08:09

Yichaoz