Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove options that are selected from all dropdowns

I have an array of dropdowns rendered by useFieldArray() from react-form-hook and mapped to react to jsx. The trick is to remove options from all dropdowns that are already selected.


So if there's 3 dropdowns that have array of options:

[ 'apple', 'banana', 'pineapple', 'pear', 'mango' ]

AND

1st dropdown: has apple selected

2nd: banana

3rd: pineapple

Dropdown options of all three would just show ['pear', 'mango' ] since the rest is selected.


What would be the best way to implement it in react/react with redux?

So that dropdown option list would dynamically change according to options selected

like image 291
Johnexe Avatar asked Oct 26 '25 12:10

Johnexe


1 Answers

We can use a very simple procedure here with javascript filter() function

use a state for selected items like this

const [selectedItems, setSelectedItems] = useState([])
const fruits = [ 'apple', 'banana', 'pineapple', 'pear', 'mango' ]

Then use filter before mapping the select field

<select onChange={handleSelectItem}>
    {fruits
     .filter((item) => !selectedItems.find(fruit=> item))
     .map((item) => <option value={item}>{item}</option>)}
</select>

Here filter function will keep those value only which are not in the selectedItems array.

When you select an option this handle function will be executed:

const handleSelectItem = (e) => {
    setSelectedItems([...selectedItems, e.target.value])
}

This function will add new item to the selectedItems array.

Using this procedure you will get the array you selected from the fruits with less code.

like image 93
Ahmmed Abir Avatar answered Oct 29 '25 05:10

Ahmmed Abir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!