how to remove selected option from array?

Solution 1:

For a working demo checkout here: https://codesandbox.io/s/exciting-hooks-y1k2e?file=/src/App.js:70-2286

here is what you have to do:


const AddDropDown = () => {
  const [count, setCount] = useState(0);
  const [selectedItemList, setSelectedItemList] = useState([]);
  const [currentSelectValue, setCurrentSelectValue] = useState();

  const optionsList = ["item1", "item2", "item3", "item4", "item5"];
  const renderDropdown = useCallback(() => {
    let list = [];
    let newOptionsList = optionsList.filter((option) => {
      console.log({ selectedItemList, option });
      return !selectedItemList?.includes(option);
    });
    for (let i = 0; i <= count; i++) {
      list.push(
        <div key={i}>
          <div>
            <div>
              <label>label</label>
              <select
                value={selectedItemList[i]}
                onChange={(e) => {
                  setCurrentSelectValue(e.target.value);
                }}
                disabled={i < count}
              >
                {i < count ? (
                  <option key={selectedItemList[i]} value={selectedItemList[i]}>
                    {selectedItemList[i]}
                  </option>
                ) : (
                  newOptionsList.map((option, key) => {
                    return (
                      <option key={option + key} value={option}>
                        {option}
                      </option>
                    );
                  })
                )}
              </select>
            </div>
          </div>
        </div>
      );
    }
    return list;
  }, [count, setCurrentSelectValue, selectedItemList]);

  const handleNew = (e) => {
    if (currentSelectValue) {
      setSelectedItemList((selecteds) => selecteds.concat(currentSelectValue));
      setCurrentSelectValue(null);
      setCount(count + 1);
    }
  };

  return (
    <div>
      <div>
        <div>
          <div>
            {renderDropdown()}
            {/* {selectList}
              {selectList.length < options.length - 2 ? ( */}
            <div>
              <div onClick={handleNew}>
                <div>Add New</div>
              </div>
            </div>
            {/* ) : (
                <div></div>
              )} */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddDropDown;