how to filter tags in Select component- ReactJS

Viewed 35

I have following code, and I hope you can help me to resolve my issue.

The code:

    import React from "react";
    import { Select } from "antd";

    const { Option } = Select;
    const data = [
      { id: 55, name: "Appraisals" },
      { id: 65, name: "Carpet Cleaning" },
      { id: 53, name: "Duct cleaning & antibacterial" },
      { id: 54, name: "Electrical" },
      { id: 62, name: "Handyman Services" },
      { id: 68, name: "Home Cleaning Services" }
    ];

    const App = () => (
      <Select
        mode="tags"
        style={{
          width: "100%"
        }}
        showSearch={false}
      >
        <Option value={null}>All</Option>
        {data?.map((el) => (
          <Option key={el?.id} value={el?.id}>
            {el?.name}
          </Option>
        ))}
      </Select>
    );

    export default App;

The scenario is following.

The user can select multiple options. But when the user selects "All", all the selected tags should be removed and only the "All" tag should be left.

Conversely, when the user selects "All" and then the user selects another option, "All" should removed and only the selected options should be left.

I tried to do something with onSelect and with onChange events. But they taking only current value.

How Can I achieve this result?... Please help me to resolve this problem. Thanks.

1 Answers

I was able to do it like this

import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";

const { Option } = Select;
const data = [
  { id: 55, name: "Appraisals" },
  { id: 65, name: "Carpet Cleaning" },
  { id: 53, name: "Duct cleaning & antibacterial" },
  { id: 54, name: "Electrical" },
  { id: 62, name: "Handyman Services" },
  { id: 68, name: "Home Cleaning Services" }
];

const App = () => {
  const [sel, setSel] = useState([]);
  const change = (e) => {
    if (e.lenght) return;
    if (e[e.length - 1] !== null) {
      // here any method of excluding the value of all
      setSel(e.filter(i => i !== null))
    } else {
      setSel([null]);
    }
  }

  return (
  <Select
    mode="tags"
    style={{
      width: "100%"
    }}
    onChange={(e) => {
      change(e)
      }}
    value={sel}    
  >
    <Option value={null}>All</Option>
    {data?.map((el) => (
      <Option key={el?.id} value={el?.id}>
        {el?.name}
      </Option>
    ))}
  </Select>
)};

export default App;
Related