React: How to create a select multiple input that accepting same value

1k Views Asked by At

I'm using antd library and reactJS. I want the user to be able to input multiple values into a select multiple input statement, and the user can input the same value at once. Something like: [20, 100, 100]. Currently in normal multiple or tags mode, when the user enters another input that already exists, the input will be removed. Basically, I wanted to keep it there. These are the codes I got from antd docs:

const children = [];

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select mode="tags" style={{ width: '100%' }} placeholder="Tags Mode" onChange={handleChange}>
    {children}
  </Select>,
  document.getElementById('container'),
);

I have tried:

  1. Setting a unique key for each of the values selected. But I found difficulties in modifying the current options that the user selected. There is no API provided that I can use to update the current options.

  2. Setting a unique key as the user selects the option by appending Date.now() to the key. But again, I'm not sure how to do this on the select props. Something like this:

ReactDOM.render(
  <Select
    mode="tags"
    style={{ width: "100%" }}
    placeholder="Tags Mode"
    onChange={handleChange}
    value={Date.now() + '' + selectedValue}
  >
    {children}
  </Select>

But again, selectedValue is not a valid variable that I can use.

  1. I tried adding labelInValue, but it just added the id and value, with no option to customize the id.
1

There are 1 best solutions below

4
On

Note: This solution only fix the problem that when ever we have a tag in select and you try to add the same tag, it do not remove the existing selected tag from Antd Select.

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

function App() {
  const [value, setValue] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  // const [options, setOptions] = useState([]);

  const onSelect = (value) => {
    setValue((prev) => [...prev, value]);
    setSearchValue("");

    // If you want to show tags after user added removes it, you can enable this code
    // Enable options and setOptions
    // setOptions((prev) => {
    //   const index = prev.find((o) => o.value === value);
    //   if (!index) {
    //     return [...prev, { label: value, value }];
    //   }
    //   return prev;
    // });
  };

  const onDeselect = (value) => {
    if (value !== searchValue) {
      setValue((prev) => prev.filter((v) => v !== value));
    }
    setSearchValue("");
  };

  return (
    <div className='App'>
      <Select
        // options={options}
        mode='tags'
        searchValue={searchValue}
        onSearch={setSearchValue}
        value={value}
        style={{ width: "100%" }}
        placeholder='Tags Mode'
        onSelect={onSelect}
        onDeselect={onDeselect}
      />
    </div>
  );
}

export default App;