How to use onchange with autocomplete material ui? How to use onchange with autocomplete material ui? reactjs reactjs

How to use onchange with autocomplete material ui?


If you're just trying to get the value of the input as the user types, you need to use onInputChange. The onChange handler runs when the user selects an option from the drop down.

export default function ComboBox() {  function handleInputChange(event, value) {    console.log(value);  }  return (    <Autocomplete      id="combo-box-demo"      options={top100Films}      getOptionLabel={(option: FilmOptionType) => option.title}      style={{ width: 300 }}      onInputChange={handleInputChange}      renderInput={params => (        <TextField {...params} label="Combo box" variant="outlined" fullWidth />      )}    />  );}

Codesandbox


the react SyntheticEvent set null target in an Asynchronous requests, try to use

event.persist()

on the event

https://reactjs.org/docs/events.html#event-pooling

 const handleOnChangeText=(event)=> {         event.persist();    console.log(event)        let active = true;    setOpen(true);    if (!loading) {      return undefined;    }    (async () => {      const response = await fetch('https://country.register.gov.uk/records.json?page-size=5000');      await sleep(1e3); // For demo purposes.      const countries = await response.json();      if (active) {        setOptions(Object.keys(countries).map(key => countries[key].item[0]) as CountryType[]);      }      active = false;    })();   }<Autocomplete      id="comboboxAsync"      disableOpenOnFocus      style={{ width: 300 }}      open={open}      onInputChange={handleOnChangeText}...


Id is getting retrieved under this pattern: id-option-numberOfOption, that's why I had to split the retrieved value in order to update the state

const handleAutoCompleteChange = (event, value) => {          this.setState({ ...this.state, [event.target.id.split("-")[0]]: value });          console.log([event.target.id.split("-")[0]],value);}