Good evening, i'm trying to solve a problem where the autocomplete value is reset. This happens when i'm changing the state of the UI (example in sandbox). I want the value to still be there, if a user decided to go back and change it. I don't why the autcomplete react that way, but I haven't found a solution.
Any suggestions how to solve this?
Link: https://codesandbox.io/s/sharp-diffie-6ikc6?file=/index.js
CodePudding user response:
You should use controlled version of the autocomplete. The issue is caused by onInputChange callback, which fired not just for selecting option. In your case React removes the autocomplete from DOM (because of your switch) and it fires onInputChange with empty value, so your state changes to empty string.
To avoid this you should use value and onChange instead. onChange fires only if you change the option.
const [value, setValue] = useState(null);
<Autocomplete
value={value}
disablePortal
id="combo-box-demo"
options={movies.sort(
(a, b) => -b.distributor.localeCompare(a.distributor)
)}
onChange={onInputChange}
groupBy={(option) => option.distributor}
getOptionLabel={(option) => option.movie}
sx={{ width: "100%", paddingRight: 2 }}
renderInput={(params) => (
<TextField
style={{ backgroundColor: "#fff", marginLeft: 25 }}
{...params}
label="Movie"
/>
)}
selectOnFocus={false}
/>
Check it out: https://codesandbox.io/s/peaceful-shamir-r2dwi?file=/index.js
