I am using 'Material UI' Autocomplete component to render a dropdown in my form. However, in case the user wants to edit an object then the dropdown should be displayed as autofilled with whatever value that's being fetched from the database.
I've tried to mock the situation using below code
import React, { Component } from 'react';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';
export default class Sizes extends Component {
state = {
default: []
}
componentDidMount() {
setTimeout(() => {
this.setState({ default: [...this.state.default, top100Films[37]]})
})
}
render() {
return (
<Autocomplete
id="size-small-standard"
size="small"
options={top100Films}
getOptionLabel={option => option.title}
defaultValue={this.state.default}
renderInput={params => (
<TextField
{...params}
variant="standard"
label="Size small"
placeholder="Favorites"
fullWidth
/>
)}
/>
);
}
}
Here after the component is mounted, I'm setting a timeout and returning the default value that should be displayed in the dropdown
However, it's unable to display the value in the dropdown and I'm seeing this error in console -
index.js:1375 Material-UI: the `getOptionLabel` method of useAutocomplete do not handle the options correctly.
The component expect a string but received undefined.
For the input option: [], `getOptionLabel` returns: undefined.
Apparently the state is getting updated when componentDidMount is getting called but the Autocomplete component's defaultValue prop is unable to read the same
Any idea what I might be getting wrong here?
Code sandbox link - https://codesandbox.io/s/dazzling-dirac-scxpr?fontsize=14&hidenavigation=1&theme=dark
For anyone else that comes across this, the solution to just use value
rather than defaultValue
is not sufficient. As soon as the Autocomplete loses focus it will revert back to the original value.
Manually setting the state will work however:
https://codesandbox.io/s/elegant-leavitt-v2i0h
Following reasons where your code went wrong:
1] defaultValue
takes the value which has to be selected by default, an array shouldn't be passed to this prop.
2] Until your autocomplete is not multiple
, an array can't be passed to the value
or inputValue
prop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With