reactjsselectinputdrop-down-menumaterial-ui

MUI Select Dropdown Menu Becomes Invisible But Doesn't Disappear or Lose Focus


I am using a MUI Select with the code below:

<FormControl required fullWidth size="small">
  <InputLabel id={`${elementName}-label`}>{elementLabel}</InputLabel>
  <Select
    labelId={`${elementName}-label`}
    id={`${elementName}`}
    name={`${elementName}`}
    value={elementValue}
    label={elementLabel}
    onChange={(e) => changeHandler(e, setForm)}
  >
    {elementArrayOptions.map(option => <MenuItem value={option} key={option}>{option}</MenuItem>)}
  </Select>
</FormControl>

And here is the code for the changeHandler:

const handleResultsSelect = (e, setForm) => {
  setForm(e.target.value)
}

The issue is that the Select works the first three or four times it's used, but then at around the fourth time, the dropdown menu becomes invisible, but the dropdown menu doesn't disappear — the cursor becomes a pointer whenever I hover over the place where the menu had been, and when I click the new item is selected, and the view updates. The big inconvenience is that no buttons, checkmarks, or any other inputs are clickable when this happens, meaning the view basically freezes, and the dropdown menu stays invisible but down indefinitely.

Is there a fix for this?


Solution

  • I solved it by adding a boolean state variable that determines whether the menu should show:

    const [openResultsMenu, setOpenResultsMenu] = useState(false)
    
    <FormControl required fullWidth size="small">
      <InputLabel id={`${elementName}-label`}>{elementLabel}</InputLabel>
      <Select
        labelId={`${elementName}-label`}
        id={`${elementName}`}
        name={`${elementName}`}
        value={elementValue}
        label={elementLabel}
        onClick={() => setOpenResultsMenu(true)}
        onChange={(e) => changeHandler(e, setForm)}
        MenuProps={{ open: openResultsMenu }}
      >
        {elementArrayOptions.map(option => <MenuItem value={option} key={option}>{option}</MenuItem>)}
      </Select>
    </FormControl>
    
    const handleResultsSelect = (e, setForm) => {
      setForm(e.target.value)
    }
    
    useEffect(() => {
      setOpenResultsMenu(false)
    }, [resultsName])
    

    I would love a less hacky approach if someone else can find one, but this definitely works.