I'm trying to implement AutoComplete component of MUI in React but i'm getting some errors, can't understand what am I doing wrong.
Those are the errors I get:
MUI: The value provided to Autocomplete is invalid.
None of the options match with `{"id":"2","name":"Delta Super","description":"Deltamethrin 0.025%"}`.
You can use the `isOptionEqualToValue` prop to customize the equality test.
This is my code:
function PesticideAutoComplete(props) {
const data = [
{
id: '1',
name: 'Parmenona',
description: 'Permethrin 0.020%',
},
{
id: '2',
name: 'Delta Super',
description: 'Deltamethrin 0.025%',
},
{
id: '3',
name: 'Shoam',
description: 'Bifenthrin 0.1%',
}
];
const defaultValue = { id: '1' };
const [value, setValue] = useState(defaultValue);
const defaultProps = {
options: data,
getOptionLabel: (option) => option.name,
};
return (
<Autocomplete
{...defaultProps}
id="grid-choose-pesticide"
clearOnEscape
defaultValue={defaultValue}
onChange={(event, newValue) => {
console.log(newValue);
setValue(newValue);
}}
renderInput={(params) => (
<TextField {...params} label="Pesticide" />
)}
/>
);
}
I would not use the default prop if you want to put value use the options={} props to inject the values in to the ac component.
< Autocomplete options = {data} getOptionLabel={(option) => option.name} id = "grid-choose-pesticide" clearOnEscape defaultValue = { defaultValue } onChange = { (event, newValue) => { console.log(newValue); setValue(newValue); } } renderInput = { (params) => ( < TextField { ...params } label = "Pesticide" / > ) } />
You need to override isOptionEqualToValue
in your element:
<Autocomplete
{...defaultProps}
id="grid-choose-pesticide"
clearOnEscape
defaultValue={defaultValue}
onChange={(event, newValue) => {
console.log(newValue);
setValue(newValue);
}}
renderInput={(params) => (
<TextField {...params} label="Pesticide" />
)}
isOptionEqualToValue={(option, value) => option.id === value.id}
/>
The reason this happens is that the Autocomplete compares your selected object with a predefined one in the back. You can see the full explanation in this post .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.