3
votes

I am using the Material UI Autocomplete component with multi select. It works great on desktop, but on mobile, I would like to disable keyboard input and only allow touch selection. In other words, I don't want the smartphone keyboard to appear.

I did not find any params for this in the docs: https://material-ui.com/api/autocomplete/#props

I tried to disable the TextField, but I could still enter text - it seems that the disabled param does not get added to the input field in the page source:

<Autocomplete
    disableClearable
    options={[...]}
    renderInput={(params) => <TextField {...params} label="xxx" disabled />}
    blurOnSelect="touch"
/>

I need the autocomplete component without the autocomplete feature :) - I could also switch to the default Select component, but i would like to keep autocomplete on desktop. Also, the Autocomplete component offers multi-selection with checkboxes.

2

2 Answers

1
votes

I think that you should create different component for mobile if you wish disable native keyboard. Material-ui Autocomplete is build on the Material-ui TextField component, on which one is build Select component.

This to pieces of code do the same (https://material-ui.com/components/selects/#api )

<InputLabel id="label">Age</InputLabel>
<Select labelId="label" id="select" value="20">
   <MenuItem value="10">Ten</MenuItem>
   <MenuItem value="20">Twenty</MenuItem>
</Select>

<TextField id="select" label="Age" value="20" select>
  <MenuItem value="10">Ten</MenuItem>
  <MenuItem value="20">Twenty</MenuItem>
</TextField>

So if you pass a disable prop to the TextField in your Autocomplete component your whole filed will be disable.

To resolve that you can create one component which for desktop is autocomplete and for mobile is only select field.

Edit: The regular select component does offer a way to show checkboxes: https://material-ui.com/components/selects/#multiple-select

1
votes

The reason you don't want a keyboard to appear might be that it makes the Autocomplete results move over the textfield itself like in my application:

enter image description here

Where without onscreen keyboard it would look fine:

enter image description here

To solve this "moving over the input field" you can make the position of your listbox absolute, like:

<Autocomplete
    disableClearable
    options={[...]}
    renderInput={(params) => <TextField {...params} label="xxx" disabled />}
    blurOnSelect="touch"
    ListboxProps={{ style: { position: 'absolute', backgroundColor: '#fafafa'} }}
/>

This did for some reason made the listbox lose it's background color and the listbox border, so I declared the background color in there too again, but for the rest it will keep the suggestions under the users keyboard:

enter image description here

Hope this helps. @mods If the screenshots are too big feel free to change them into urls but I think it helps describing the problem/solution.