Search code examples
javascriptreactjsmaterial-ui

Material UI Autocomplete: highlighted option should become input value


When a user browses through the options using the arrow keys on his keyboard, I take the value from the highlighted option and use it as the current input value (input here has its own state).

Unfortunately, the highlighted state of the option is lost upon saving the title or value of the option as the input. Is there a way to not lose it?

Here is an example:

https://codesandbox.io/s/modern-rgb-5tew1p?file=/demo.tsx

P.S.: Although this property sounded like it was made for it, includeInputInList does not help.

Thanks in advance!


Solution

  • Try this (I made some changes to your code like adding reason and isOptionEqualToValue):

    export default function ComboBox() {
      const [input, setInput] = React.useState(null);
    
      const handleInputChange = (event, value) => {
        setInput(value);
      };
    
      const handleHighlightChange = (event, option, reason) => {
        if (option && reason === "keyboard") {
          setInput(option);
        }
      };
    
      const handleFilterOptions = (currentOptions) => currentOptions;
    
      return (
        <Autocomplete
          id="combo-box-demo"
          value={input}
          onChange={handleInputChange}
          options={top100Films}
          isOptionEqualToValue={(option, value) => option.label === value.label}
          includeInputInList={true}
          onHighlightChange={handleHighlightChange}
          getOptionLabel={(option) => option.label}
          filterOptions={handleFilterOptions}
          style={{ width: 300 }}
          renderInput={(params) => (
            <TextField {...params} label="Combo box" variant="outlined" />
          )}
        />
      );
    }