skip to Main Content

So i am trying to implement a multiselect dropdown in material ui with the following conditions
The dropdown will have [0 Apples, 1 Oranges, 2 Grapes]

By default 0 Apples should be selected
None of the options can be unselected.

If 0 Apples is selected and the user selects 1 Oranges or 2 Grapes then 0 Apples will be unselected and either 1 Orange or 2 Grapes will be selected depending on what he selected.

If 1 Oranges is selected then 0 Apples will get unselected.
If 2 Grapes Is selected then 0 Apples will get unselected.

If 1 Oranges is selected 2 Grapes is selected then both of them will get selected.
If 2 Grapes is selected 1 Oranges is selected then both the will get selected.

I am having problems trying to implement the unselect logic for the following cases:
1 Oranges and 2 Grapes is selected then unselect either of them.

And i am not sure where it is not working. The variable actualNewSelectionByUser is empty because he is unselecting so i will read from actualSelected as in value of mui input. I will use this to delete the value in state. But this is not working.

Here is the code sandbox link

link to code sandbox

2

Answers


  1. Chosen as BEST ANSWER

    So I figured this out, working on the shortcoming of Shanka's answer I implemented the following: Handles the case of length being 0 and if the last selected item is 0.

      const handleChange = (incomingValues) => {
        const {
          target: { value },
        } = incomingValues;
        let newValues;
        if (value?.length === 0 || value[value?.length - 1] == 0) {
          newValues = [0];
        } else if (value?.includes(1) || value?.includes(2)) {
          newValues = value.filter((item) => item !== 0);
        } else {
          newValues = values;
        }
        setValues(newValues)
      }
    

    The last selected item in the multiple Select component will be the last item in the array.


  2. Here you have to update your handleChange logic.

    const handleChange = (event) => {
      const {
        target: { value },
      } = event;
    
      let newValues;
    
      // If the user selects "Apples" (index 0), reset the selection to only include "Apples"
      if (value.includes(0)) {
        newValues = [0];
      } 
      // If the user selects "Oranges" (index 1) or "Grapes" (index 2), remove "Apples" and toggle the selected value
      else if (value.includes(1) || value.includes(2)) {
        newValues = value.filter(v => v !== 0);  // Remove "Apples" (index 0) from the selection
      } 
      // If the user tries to deselect the last remaining selected item, reset to "Apples"
      else if (value.length === 0) {
        newValues = [0];
      } 
      // For any other case, keep the value as is
      else {
        newValues = value;
      }
    
      setValues(newValues);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search