How to get value of Dropdown component in Ant Design (Antd), React js

Viewed 2594

I have an issue that I can not take out the value of Dropdown to setState or something like that. Does everyone know how to fix it? I tried to access on it by onChange but still not working.

The code is below:

const menu = (
    <Menu onSelect={(e) => console.log(e)}>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Recommended
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Newest
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Lowest Price
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer">
          Highest Price
        </a>
      </Menu.Item>
    </Menu>
  );


<Dropdown overlay={menu1} trigger={['click']}>
            <a
              className="ant-dropdown-link"
              onClick={(e) => e.preventDefault()}
              style={{ color: '#d46b08', fontWeight: 'bold' }}
            >
              PRICE <DownOutlined />
            </a>
</Dropdown> ```
2 Answers

In order to get the value of the selected menu on dropdown, you need to assign a key on each menu item and then you can use onClick prop of the Menu component to get the value or the key.

const handleClick = ({key}) => {
  console.log(key)
  //you can perform setState here
}

const menu = (
  <Menu onClick={handleClick}>
    <Menu.Item key="Recommend">Recommend</Menu.Item>
    <Menu.Item key="Newest">Newest</Menu.Item>
    <Menu.Item key="Lowest Price">Lowest Price</Menu.Item>
    <Menu.Item key="Highest Price">Highest Price</Menu.Item>
  </Menu>
);

<Dropdown overlay={menu} trigger={["click"]}>
    <a
      className="ant-dropdown-link"
      onClick={(e) => e.preventDefault()}
      style={{ color: "#d46b08", fontWeight: "bold" }}
    >
      PRICE <DownOutlined />
    </a>
</Dropdown>

check it working here for reference.

The Dropdown component does not call any onChange property. It has onVisibleChange property that gets called every time the "dropdown trigger" (be it hover, click, right-click) is done. Do something like this:

const SomeComponent = _props =>
{
  const [visible, setVisible] = React.useState(false);
  
  return (<Dropdown overlay={menu} visible={visible} onVisibleChange={isVisible => setVisible(isVisible)} >
    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
      Hover me <DownOutlined />
    </a>
  </Dropdown>);
}

Working pen here

Related