Peter Alfvin
Peter Alfvin

Reputation: 29419

How do I disable TextField input with MUI Autocomplete?

I'm using Autocomplete with TextField for renderInput throughout my app for form field input, but have one case where I don't want to allow any text input and only permit the selection of one of the dropdown elements.

If I switch to the more natural Select component, however, the styling of the dropdown elements is different. In particular, the width of the options doesn't seem to be inherited from the FormControl element.

If I use Autocomplete and use dev tools in the browser to set the disabled property of the input element, everything behaves as I would like. But if I pass inputProps={{disabled: true}} to TextField, things blow up when I click the dropdown.

Any suggestions?

Upvotes: 6

Views: 11501

Answers (1)

Dmitriif
Dmitriif

Reputation: 2433

You should rewrite readOnly attribute of a native input element to true via inputProps of renderInput to achieve the desired result:

    <Autocomplete
      renderInput={({ inputProps, ...rest }) =>    <TextField
      {...rest}
      inputProps={{ ...inputProps, readOnly: true }}
    />

Demo

Upvotes: 14

Related Questions