Home > Enterprise >  how to filter already selected option from select reactjs?
how to filter already selected option from select reactjs?

Time:07-15

I have a mapped Select component that has a list of names. I need to filter out the name that has been already selected in one Select Component and not show in others. (i.e only show non-selected values in other Select Components).

I tried to store the selected name in a state and filter it out and map the names in the option. But that seems to limit only for 2 select i.e in select one I selected a name, and that name is successfully not shown in the second select. If I select a name in the second selection, the first selected value is available in the third one.

Code:

const App = () => {
  const names = ["jack", "lucy", "leo", "patrick", "joe", "rio"]; //got from api
  const dummyData = ["Select One", "Select Two", "Select Three", "Select Four"]; //got from api
  const [selected, setSelected] = React.useState([]);
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column"
      }}
    >
      {dummyData.map((data, index) => (
        <div style={{ marginTop: "20px" }}>
        <Popover
        trigger="click"
        content={
          <Select
            key={index}
            placeholder="Select"
            onChange={(value) => {
              setSelected(value);
            }}
            style={{
              width: 120
            }}
          >
            {names
              .filter((n) => !selected.includes(n))
              .map((name) => (
                <Option value={name}>{name}</Option>
              ))}
          </Select>
        }
      >
        Click {index}
      </Popover>
        </div>
      ))}
    </div>
  );
};

The above issue can be solved by storing the selected name in a list. But in that case, if I select a name from select one component and change the name to another, both the values are added to the list, which gets filtered in other components even though the name isn't selected.

Eg: If I select "jack" in the first Select it is added to the list, and if I change from "jack" to "leo", leo is also added to the list, by this second Select component misses out both "jack" and "leo" instead of just "leo".

Expected behavior: If I select "jack" from first Select it should show in other Select components.

Note: This Select is inside its own Popover component.

Codesandbox: https://codesandbox.io/s/three-ways-to-trigger-antd-4-21-6-forked-nxiph8?file=/demo.js

CodePudding user response:

You can store, the selected names in a list, just update the list accordingly in onChange, like this:

onChange={(value) => {
           const array = [...selected];
           array[index] = value;
           setSelected(array);
        }};

Check it working here.

  • Related