moroshko / react-autosuggest

WAI-ARIA compliant React autosuggest component
http://react-autosuggest.js.org
MIT License
5.97k stars 586 forks source link

Detect suggestions visible #580

Open jeffkreska opened 6 years ago

jeffkreska commented 6 years ago

Are you reporting a bug?

No

Are you making a feature request?

Yes

orenh1 commented 5 years ago

I would also like this feature, but my use-case is different:

I use the AutoSuggest component in a dialog box. I would like the Enter key to act as if the default button in the dialog box was clicked.

However, the Enter key should behave differently depending on whether the Suggestions are visible or not:

  1. When they're visible: Enter should select the currently highlighted item.
  2. When they're invisible: Enter should act like the dialog box's button has been clicked.

This leads to a great user flow:

  1. Open the dialog box
  2. Type 2-3 characters
  3. Thanks to "highlightFirstSuggestion", the desired result is already highlighted
  4. Press 'Enter' once to select the first suggestion. The input field fills in with the full text of the first suggestion, and the suggestions list disappears.
  5. Press 'Enter' a second time to submit the dialog box.

To be clear, I don't need the component to tell me when Enter was clicked. I can get that information using a keypress handler. I only need to know whether the Suggestions list is visible.

grantmr commented 4 years ago

I also have the use case mentioned by @orenh1 I'm finding that after the first Enter press, the suggestions disappear and highlightFirstSuggestion is selecting the first suggestion in the list and not the one the user selected, so the second Enter press actually submits that newer, hidden selection. Haven't as such found a way to prevent this, but doing highlightFirstSuggestion only when the suggestions are visible would prevent this.

VilleKylmamaa commented 2 years ago

To help you detect whether suggestions are visible, you can access Autosuggest state's isCollapsed and isFocused by giving it ref:

<Autosuggest
    ...
    ref={this.autosuggestRef}
/>

And then calling:

this.autosuggestRef.current.state.isCollapsed or this.autosuggestRef.current.state.isFocused for the respective state variables.