Home > Software engineering >  Can not deselect from MUI select Component. What's the right way?
Can not deselect from MUI select Component. What's the right way?

Time:01-02

I am trying to implement deselect option in material UI select component.My question is 'is there any prop that automatically deselect the selected object after clicking the selected Object?'

my code snippet:

<FormControl>
  <InputLabel>{t('typeUsers')}</InputLabel>
  <Select
    label={t('typeUsers')}
    value={filterUser}
    onChange={(e) => { setFilterUser(e.target.value); }}
  >
   {Object.values(users).filter((user) => (user.administrator === false)).map((user) => (<MenuItem key={user.id} value={user.id}>{user.name}</MenuItem>))}
 </Select>
</FormControl>

OR how can I add an additional MenuItem that sets selected Item deslected?

CodePudding user response:

Add the following menu item above where you iterate through users

<MenuItem key='clear' value='clear'>Clear selection</MenuItem>

And here is the onChange for the Select component

onChange={e => setFilterUser(e.target.value === 'clear' ? '' : e.target.value)}
<FormControl>
  <InputLabel>{t('typeUsers')}</InputLabel>
  <Select
    label={t('typeUsers')}
    value={filterUser}
    onChange={e => setFilterUser(e.target.value === 'clear' ? '' : e.target.value)}
  >
   <MenuItem key='clear' value='clear'>Clear selection</MenuItem>
   {Object.values(users).filter((user) => (user.administrator === false)).map((user) => (<MenuItem key={user.id} value={user.id}>{user.name}</MenuItem>))}
 </Select>
</FormControl>
  • Related