Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
React: Why does autocomplete unintentionally reset the selected value?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!