I want to display the name of the selected item on the button.
Currently, the button says Select User Name but when someone selects a name, that name should be displayed instead.
CodePudding user response:
Try this , it works for me
const App = () => {
const [itemName, setItemName] = useState("Select User Name");
const items = [
{ key: "1", label: "John" },
{ key: "2", label: "Peepo" },
{ key: "3", label: "Patel" },
{ key: "4", label: "Soukup" }
];
const menu = (
<Menu
items={items}
onClick={({ key }) => {
setItemName(items.find((elm) => elm.key === key).label);
}}
/>
);
CodePudding user response:
You can use this approach of displaying the name on the button. On making an item as an object and passing it to the items params.
import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Menu, Dropdown, Button, Space } from "antd";
const App = () => {
const [itemName, setItemName] = useState("Select User Name");
const items = [
{ key: "1", label: "John" },
{ key: "2", label: "Peepo" },
{ key: "3", label: "Patel" },
{ key: "4", label: "Soukup" }
];
const menu = (
<Menu
items={items}
selectable
onSelect={({ key }) => {
setItemName(items[key - 1].label)
}}
/>
);
return (
<>
<h3>Selected user name should appear on the button</h3>
<Dropdown overlay={menu}>
<Button type="primary">
<Space>{itemName}</Space>
</Button>
</Dropdown>
</>
);
};
export default App;