Search code examples
reactjsdrop-down-menuantd

Antd searchable Dropdown with checkbox


I am using antd NPM package to create a searchable dropdown like the below, enter image description here

Using Menu as below,

<Menu.Item key="btc">BTC1
   <Checkbox style={{ float: "right" }} />
</Menu.Item>

I am trying to add a search filter in the dropdown but cannot figure out the solution.

Highly appreciate any help.


Solution

  • I did it using dropdownRender with antd Select component,

    <Select
        optionLabelProp="label"
        bordered={false}
        value={selectedItems}
        mode="multiple"
        defaultValue={defaultValue}
        searchValue=""
        onChange={handleChange}
        dropdownRender={() => {
          return <>{menu}</>
        }}
        maxLength={2}
        maxTagCount={2}
        showArrow
        showSearch={false}
        className="filtertered-dropdown-select"/>
    

    The menu,

      const menu = (
        <Menu className="ant-dropdown-menu" style={{ alignContent: 'center' }}>
          <Menu.Item>
            <Input
              placeholder="Input search text"
              prefix={<SearchOutlined />}
              value={clearSearch}
              autoFocus
              onChange={e => {
                setFilteredItems(
                  dropdownValues.filter(original => original.value.toLowerCase().startsWith(e.target.value.toLowerCase()))
                )
              }}
            />
          </Menu.Item>
          _.chain(filteredItems)
                .groupBy('category')
                .map((value, key) => {
                  if (key && key !== 'undefined') {
                    return (
                      <Menu.ItemGroup key={key.toLowerCase()} title={key}>
                        {menuItems(value)}
                      </Menu.ItemGroup>
                    )
                  }
                  return menuItems(value)
                })
                .value()
        </Menu>
      )
    

    MunuItems,

    const menuItems = items =>
      items.map((item, index) => {
        return (
          <Menu.Item
            key={item.value}
            onClick={e => {
              if (selectedItems.includes(item.label)) {
                const newArray = selectedItems.filter(val => val !== item.label)
                setSelectedItems(newArray)
              } else {
                const newArray = [...selectedItems, item.label]
                setSelectedItems(newArray)
              }
            }}
          >
          {item.label}
          <Checkbox style={{ float: 'right' }} checked={selectedItems.includes(item.label)} />
        </Menu.Item>
      )
    })
    

    Hope it helps someone.