reactjsreact-hooksmaterial-uimui-autocomplete

How to use onchange with Material UI autocomplete?


With the method handleChange is handled OnChange event of the Form Input with Hooks style that set the state off the object.

The handleChange function in turn calls setLocation which updates the location state with the new value.

To make user data entry easier, I decided to change the city field to an autocomplete, but I failed to capture the value of the autocomplete. In the documentation he tells me that I need to pass two arguments but I can't understand very well

function(event: object, value: any) => void
event: The event source of the callback
value: null

How can I access the value of the field and put it into my function to insert the data?

        <Autocomplete
        style={{ width: 300 }}
        value={location.City}
        onChange={handleChange}
        options={list.City}
        classes={{
          option: classes.option,
        }}
        autoHighlight
        getOptionLabel={option => typeof option === 'string' ? option : option.City}
        renderOption={option => (
          <React.Fragment>

            {option.City} -{option.State}
          </React.Fragment>
        )}

         renderInput={params => (
           <TextField {...params} label="City"  value={location.City}  margin="normal" variant="outlined" style={{ width: 220 }} inputProps={{
             ...params.inputProps,
             autoComplete: 'disabled', // disable autocomplete and autofill
           }}/>
         )}
       />

Solution

  • 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