5

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!

asked Oct 12, 2022 at 7:30
1

2 Answers 2

3

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" />
 )}
 />
 );
}
answered Oct 12, 2022 at 13:39
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use autoSelect options

answered Sep 2, 2024 at 12:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.