I'm trying to use a MUI Autocomplete component (v5.11) like shown in the example:
import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
const options = ['Option 1', 'Option 2'];
export default function ControllableStates() {
const [value, setValue] = React.useState<string | null>(options[0]);
const [inputValue, setInputValue] = React.useState('');
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
value={value}
onChange={(event: any, newValue: string | null) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" />}
/>
</div>
);
}
But I do get two typescript errors (using v4.7.4):
value
Type 'string' is not assignable to type 'string[]'.ts(2322)
useAutocomplete.d.ts(292, 3): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & AutocompleteProps<string, undefined, undefined, undefined, "div">'
onChange
Type '(event: any, newValue: string | null) => void' is not assignable to type '(event: SyntheticEvent<Element, Event>, value: string[], reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<string>) => void'.
Types of parameters 'newValue' and 'value' are incompatible.
Type 'string[]' is not assignable to type 'string'.ts(2322)
useAutocomplete.d.ts(217, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & AutocompleteProps<string, undefined, undefined, undefined, "div">'
I don't see, what is going wrong, as I just used the MUI example without any changes. And of course value
should be a single string, while the options are an array.
Update
Here you can see the configuration, which results in the typescript error: Codesandbox
CodePudding user response:
set multiple={false}
in the autocomplete
<Autocomplete
multiple={false}
value={value}
onChange={(event: any, newValue: string | null) => {
setValue(newValue);
}}
FYI - by default it should come as false but for some reason, have to explicitly set it to false in the code sandbox