React select remove selected option on search

react-select has a prop called filterOption where you can pass custom filter logic.

Check this CodeSandbox link to see my implementation.

import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" },
  { value: "Apple", label: "apple" },
  { value: "Orange", label: "orange" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState([]); //add initial state

  const handleChange = (selectedOption) => {
    setSelectedOption(selectedOption);
  };

  const filterOptions = (candidate, input) => {
    if (input) {
      if (candidate.label.toLowerCase().includes(input.toLowerCase()))
        return true;
      if (
        selectedOption.some((opt) => {
          if (opt.value === candidate.value) return true;
          else return false;
        })
      )
        return true;
      return false;
    }
    return true;
  };

  return (
    <div className="App">
      <Select
        defaultValue={{ value: "chocolate", label: "Chocolate" }} // default value must be like this.
        value={selectedOption}
        onChange={handleChange}
        options={options}
        isMulti
        hideSelectedOptions={false}
        isSearchable
        filterOption={filterOptions}
      />
    </div>
  );
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top