reactjs / react-autocomplete

WAI-ARIA compliant React autocomplete (combobox) component
MIT License
2.17k stars 532 forks source link

Hide the autocompleter when empty #216

Closed fredriksundstrom closed 7 years ago

fredriksundstrom commented 7 years ago

Hi! I read at https://github.com/reactjs/react-autocomplete/tree/master/examples/managed-menu-visibility that I can indeed control if the menu is open or closed manually. But is there a way to not show the empty autocompleter when I focus? Using a onFocus didn’t do anything for me, and since I have not yet done any onChange, I can’t seem to control it. I only wanna show it when a search has begun.

What would be a good strategy to handle it?

skarmavbild 2017-03-16 kl 17 09 05
fredriksundstrom commented 7 years ago

I could achieve it with changing

onMenuVisibilityChange={isOpen => this.setState({ isOpen })}

to this:

onMenuVisibilityChange={isOpen => this.setState({ open })}

...from the example I provided a link to. Don’t know if it’s the correct approach, but it seems to do the trick! (The default isOpen is set to false.)

CMTegner commented 7 years ago

But is there a way to not show the empty autocompleter when I focus?

There are two ways you can go about this:

  1. When there are no items to be displayed the menu container will be empty (assuming you haven't overridden props.renderMenu). If you avoid adding padding to the menu container it should be invisible (i.e. 0px height) when there are no matches.
  2. Override props.renderMenu and return null when there are no matches (by checking the items parameter).

If you want to force the menu to stay open (e.g. for debugging) you can use props.open: <Autocomplete open />

mikelambert commented 7 years ago

FYI, returning null does not appear to work, because null is then passed into React.cloneElement, which throws an Exception. I'm returning an empty <div/> to work around this.

mmanweihuang commented 6 years ago

Or you can fix this by setting padding to 0 in menuStyle.

ranjitsachin commented 5 years ago

Or you can check if input value through css, if its empyt then make it sibling div is display is none. Its simple css solution.

searchTermField[value=""] + div { /// SearchTermField is input box.

display: none; }