1

How to disable the selected option in the list of options in autocomplete PrimeReact?

For example, after selecting an option "Afghanistan", it should be disabled right away.

example

CodeSandbox:

Edit awesome-shockley-n201lg

Code Sample:

export const AutoCompleteDemo = () => {
//...

  const searchCountry = (event) => {
    setTimeout(() => {
      let _filteredCountries;
      if (!event.query.trim().length) {
        _filteredCountries = [...countries];
      } else {
        _filteredCountries = countries.filter((country) => {
          return country.name
            .toLowerCase()
            .startsWith(event.query.toLowerCase());
        });
      }

      setFilteredCountries(_filteredCountries);
    }, 250);
  };

  const itemTemplate = (item) => {
    return (
      <div className="country-item">
        <div>{item.name}</div>
      </div>
    );
  };

  return (
    <div className="card">
      <AutoComplete
        value={selectedCountry2}
        suggestions={filteredCountries}
        completeMethod={searchCountry}
        field="name"
        dropdown
        forceSelection
        itemTemplate={itemTemplate}
        onChange={(e) => setSelectedCountry2(e.value)}
        aria-label="Countries"
      />
    </div>
  );
};
jhon26
  • 313
  • 2
  • 11

2 Answers2

2

This has been deployed in PrimeReact 9.0.0-beta1 that is now in NPM.

Here is a working Code Sandbox:https://codesandbox.io/s/lingering-darkness-vyhp33

const onChange = (e) => {
    e.value.disabled = true;
    setSelectedCountry2(e.value);
};
Melloware
  • 10,435
  • 2
  • 32
  • 62
  • Sorry Melloware, i dont want to permanantly disable an option. Instead, i want to disable the option after selection. Which props should i use in this case? without modifying countries.json data – jhon26 Jan 27 '23 at 13:35
  • 1
    OK I just updated my Sandbox to do what you want...check again. – Melloware Jan 27 '23 at 15:12
  • Thank you so much Melloware, a very usefull answer ! – jhon26 Jan 27 '23 at 15:55
0

It worked for me with the onSelect and onUnselect props. Here the example:

<AutoComplete
  name="name"
  field="name"
  completeMethod={search}
  value={selectedCountries} 
  suggestions={filteredCountries} 
  onSelect={(e) => e.value.disabled = true}
  onUnselect={(e) => e.value.disabled = false}
  onChange={(e) => {
    setSelectedCountries(e.value)
  }}
  multiple
/>