Home > Back-end >  How can we get value of selected menu item in Ant Design?
How can we get value of selected menu item in Ant Design?

Time:08-20

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.

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;
  • Related