Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda