Take a look at this example that demonstrates the use of optionLabelProp
within the <Select/>
component
https://i.sstatic.net/vUl4c.png
<Select optionLabelProp="label"> /* Include optionLabelProp here */
{items.map((task) => {
return (
<Option value={task.value} label={task.label}> /* Add label here */
{task.label}
</Option>
);
})}
</Select>
Example
App.jsx
import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { DeleteOutlined } from "@ant-design/icons";
import { Select } from "antd";
const App = () => {
const { Option } = Select;
const [items, setItems] = useState([
{
id: 1,
value: "james",
label: "James"
},
{
id: 2,
value: "lucy",
label: "Lucy"
},
{
id: 3,
value: "lisa",
label: "Lisa"
},
{
id: 4,
value: "peter",
label: "Peter"
}
]);
const handleChange = (value) => {
console.log(`selected ${value}`);
};
const deleteOption = (value) => {
setItems(
items.filter((item) => {
return item.value !== value;
})
);
console.log("deleted", value);
};
return (
<>
<Select
defaultValue="lucy"
optionLabelProp="label"
style={{
width: 170
}}
onChange={handleChange}
>
{items !== undefined &&
items.map((task) => {
return (
<Option key={task.id} value={task.value} label={task.label}>
<span>{task.label}</span>
<span style={{ float: "right" }}>
<DeleteOutlined
onClick={(e) => {
e.stopPropagation(); /* Include e.stopPropagation() */
deleteOption(task.value);
}}
/>
</span>
</Option>
);
})}
</Select>
</>
);
};
export default App;
Output:
https://i.sstatic.net/05rja.gif
https://i.sstatic.net/5EZ2w.png
Update:
Add e.stopPropagation()
to fix selection issue while deleting the option
<DeleteOutlined
onClick={(e) => {
e.stopPropagation(); /* Include e.stopPropagation() */
deleteOption(task.value);
}}
/>
Hope this explanation is beneficial! Appreciate your time :)