Search code examples
javascriptreactjsantd

How to change select component tags in ant design


Hi everyone I have the following code.

I am trying to do following.

When the user selects one of the items from the dropdown list, it appears in select with a close tag.

So I need somehow customize and add besides that close icon also edit button. How can I achieve that?

    import React from "react";
    import "antd/dist/antd.css";
    import { Select } from "and";

    const { Option } = Select;
    const arr = ["first value", "second value", "third value"];
    const App = () => {
      return (
        <>
          <Select
            mode="tags"
            size={"large"}
            placeholder="Please select"
            style={{
              width: "100%"
            }}
          >
            {arr?.map((el) => (
              <Option key={el} value={el}>
                {el}
              </Option>
            ))}
          </Select>
        </>
      );
    };

    export default App;

P.S. unfortunately I am using antd version 3.x.xand it does not support tagRender prop. And there is no way to upgrade to the latest version.

Please help me to resolve this problem.


Solution

  • As a workaround solution for antd version 3.3.0; You can add a custom icon to all the options and hide these icons when they are in the select dropdown like this:

    import React from "react";
    import "antd/dist/antd.css";
    import { Select } from "antd";
    import { EditOutlined } from "@ant-design/icons";
    import "./demo.css";
    const { Option } = Select;
    const arr = ["first value", "second value", "third value"];
    
    const App = () => {
      const handleEditClicked = (e, el) => {
        e.stopPropagation();
        e.preventDefault();
    
        console.log(el);
      };
    
      return (
        <>
          <Select
            mode="tags"
            size={"large"}
            placeholder="Please select"
            style={{
              width: "100%"
            }}
          >
            {arr?.map((el) => (
              <Option key={el} value={el}>
                <EditOutlined
                  className="customEditIcon"
                  onClick={(e) => handleEditClicked(e, el)}
                />
                {el}
              </Option>
            ))}
          </Select>
        </>
      );
    };
    
    export default App;
    

    And this is the related css to hide icons on dropdown:

    .customEditIcon.anticon-edit:before {
      display: none;
    }
    
    .ant-select-dropdown .customEditIcon {
      display: none;
    }
    

    You can take a look at this forked sandbox for a live working example of this workaround solution.