marmelab / react-admin

A frontend Framework for single-page applications on top of REST/GraphQL APIs, using TypeScript, React and Material Design
http://marmelab.com/react-admin
MIT License
24.79k stars 5.23k forks source link

AutocompleteInput selects a value other than the highlighted one #9593

Open MatthiasLinster opened 8 months ago

MatthiasLinster commented 8 months ago

What you were expecting:

We are using an AutcompleteInput with options provided by an external backend. In particular, the backend yields filtered and sorted options based on the user's input. We keep track of the user input within a React state (updated by the onInputChange callback), which is in turn passed to React/Tanstack query to fetch the options. The order of the search results is only stable for the same query string, i.e. can change if you type further characters.

While this works fine, we get some flaky highlighting behavior when we set autoHighlight to true. According to the MUI documentation, this prop selects the first element in the list. That is, once you press "Enter", you select the first element. While the selection works fine, the first option is not always highlighted although it will be selected when you press "Enter".

What happened instead: The highlighted option is not the first one. Sometimes, there is even no highlighted option at all.

Steps to reproduce:

  1. Go to https://stackblitz.com/edit/github-fvmfaw?file=src%2FCreateView.tsx
  2. Click on the add button.
  3. Type "duc" into the autocomplete field. The option "duck1" will be correctly highlighted.
  4. Press backspace to remove "uc" so that you end up with "d" in the autocomplete field. Now, "duck1" is highlighted although it is not the first option.
  5. Press enter. "dog1" is selected although "duck1" is highlighted.

Related code: https://stackblitz.com/edit/github-fvmfaw?file=src%2FCreateView.tsx

Other information: The same example works with Material UI, see https://stackblitz.com/edit/stackblitz-starters-wxu1kv?file=src%2FApp.tsx

Environment

slax57 commented 8 months ago

Idk why, trying your stackblitz raised an error

image

Although I managed to create a working stackblitz with the same code, and indeed I can reproduce the issue there.

Thanks for the report!

adguernier commented 5 months ago

IMO and after some investigations, setting your own state to change the choices collides with the <AutocompleteInput> logic and it leads to this behavior. I think a good way to achieve what you want to do, is to follow the the React-admin way, taking inspiration from the <ReferenceInput>. This component fetches choices and creates a ChoicesContext used by <AutocompleteInput>. To conclude, for me this is not a bug.