简体   繁体   中英

How can we get value of selected menu item in Ant Design?

Sandbox Link

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.

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);
     }}
   />
 );

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM