How to disable one of the list item in PrimeReact ListBox?

Viewed 289

For the PrimeReact ListBox implementation:

const cities = [
    {name: 'New York', code: 'NY'},
    {name: 'Rome', code: 'RM'},
    {name: 'London', code: 'LDN'},
    {name: 'Istanbul', code: 'IST'},
    {name: 'Paris', code: 'PRS'}
];

<ListBox 
  optionLabel="name" 
  optionValue="code" 
  value={city} 
  options={cities} 
  onChange={(e) => setCity(e.value)} 
/>

I get the proper panel with the list items. But How do I disable a list item, say if New York needs to be disabled from getting selected, how can it be achieved?

1 Answers

Solution is to either pass name of the property to match disabled state to of the option like this:

const cities = [
  { name: 'New York', code: 'NY', disabled: true },
  { name: 'Rome', code: 'RM' },
  { name: 'London', code: 'LDN' },
  { name: 'Istanbul', code: 'IST' },
  { name: 'Paris', code: 'PRS' },
];

<ListBox
  optionLabel="name"
  optionValue="code"
  value={city}
  options={cities}
  optionDisabled="disabled"
  onChange={(e) => setCity(e.value)}
/>

Or a function that will decide which one is disabled, where option is one item in the list while list is being iterated

const cities = [
  { name: 'New York', code: 'NY' },
  { name: 'Rome', code: 'RM' },
  { name: 'London', code: 'LDN' },
  { name: 'Istanbul', code: 'IST' },
  { name: 'Paris', code: 'PRS' },
];

<ListBox
  optionLabel="name"
  optionValue="code"
  value={city}
  options={cities}
  optionDisabled={(option) => option.name === 'New York"}
  onChange={(e) => setCity(e.value)}
/>
Related