Home > Net >  How to exclude some options from React Select options
How to exclude some options from React Select options

Time:05-15

I have around 50 options to be shown in the react select options. But I want to exclude some of the options with logic to already posted values. The purpose is, that we have a form where we add values from the drop-down list. if one item is been added then that should not have to be shown in the dropdown list.

refactored code:

export default function App() {
  const choices = [
    {
      value: 0,
      label: "Container empty to shipper"
    },
    {
      value: 1,
      label: "Container pickup at shipper"
    },
    {
      value: 2,
      label: "Container arrival at first POL (Gate in)"
    },
    {
      value: 3,
      label: "Container loaded at first POL"
    }
  ];

  const postedList = [
    "Container empty to shipper",
    "Container pickup at shipper"
  ];
  return (
    <div className="App">
      <h1>Select Box</h1>
      <Select
        isClearable={false}
        // here the choices should be 2 eliminating the other 2 whose labels are matching to postedlist 
        options={choices}
        defaultValue={choices[0]}
        onChange={(choice) => console.log(choice.value)}
      />
    </div>
  );
}

Currently, it's rendering all 4 choices available but I want to return only 2 of them whose labels are not matching to postedlist

I also have created Edit happy-wave-yktw2j

CodePudding user response:

You can dynamically filter items and exclude them with the includes method.

    <Select
    options = {choices.filter((choice) => !postedList.includes(choice.label))}
    ...
    />
  • Related