Enable React-Select option to persist during search?

76 Views Asked by At

I am attempting to make the first and last option in my react-select component always display in the list. I don't want it to be filtered out during search. Is there a way to eliminate an item from being filtered? I have tried a custom filter see codesandbox link, but it doesn't work. If I search for a or letter not in the first or last item, it gets removed. Can anyone provide any assistance? See relevant snippet below:

    const customFilter = (option, rawInput) => {
    const inputValue = rawInput.toLowerCase();

    // If there's no input, include all options
    if (!inputValue) {
      return true;
    }

    // Allow the first and last options to always be visible
    if (option.index === 0 || option.index === options.length - 1) {
      return true;
    }

    // Apply regular filtering for other options
    return (
      option.label.toLowerCase().includes(inputValue) ||
      option.value.toLowerCase().includes(inputValue)
    );
  };

  return (
    <>
      <Select
        options={options}
        isSearchable={true}
        filterOption={customFilter}
      />
    </>
  );
};
1

There are 1 best solutions below

0
On

Forked Sandbox Link - https://codesandbox.io/s/still-moon-8wwczj

import Select from 'react-select';


function App() {
  const options = [
    { value: 'first', label: 'first', fixed: true },
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'last', label: 'last', fixed: true },
  ]

  const customFilter = (option, rawInput) => {
    const inputValue = rawInput.toLowerCase();

    // If there's no input, include all options
    if (!inputValue) {
      return true;
    }

    // Allow the first and last options to always be visible
    if (option.data.fixed) {
      console.log("from option fixed ====>", option);
      return true;
    }

    // Apply regular filtering for other options
    return (
      option.label.toLowerCase().includes(inputValue) ||
      option.value.toLowerCase().includes(inputValue)
    );
  }

  return (
    <div className="App">
      <Select
        options={options}
        isSearchable={true}
        filterOption={customFilter}
      />
    </div>
  );
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Here is an example of how you can fix the first and last item.

Explanation: If you check the options array, you will see a key named fixed. If fixed is true, then those items will show always no matter what. You just need to add fixed as true for the first and last item of the options or into whichever item you want to fix.