Search code examples
reactjsantd

How to get id of selected Select component in Ant Design


I want to get selected id of Select component in Ant design, the current time, Select of Ant Design return selected value is value of Options, I can set value={item.id} but when Select component is selected, it will display the id, not name of selected Option, so I must set value={item.name} and onChange handler will take item.id. How can I do it?

This is my sample Codesanbox

Update: I realize that in my real project, I return Option with condition, if I remove condition, it's return selected id and show selected name, exacly what I want, what is wrong with my code?

  const userOptions = user.map((item, index) => {
    if (!existedUser.some((current) => current.id === item.id)) {
      return (
        <Option key={index} value={item.id}>{item.name}</Option>
      );
    }
  });

Solution

  • if you are passing options to <Select />, you can pass the options as {label: item.name, value: item.id}, keep in mind that the change functions will now recieve {label: ..., value: ...} so if you want the id you'll have to get it by accessing .value.