react-select How to hide dropdown menu programmatically when 'no results found' is shown?

Sabbiu Shah picture Sabbiu Shah · Mar 22, 2018 · Viewed 10.2k times · Source

Github Repo: react-select

After searching in the select box:

enter image description here

After typing a text that is not in the dropdown and enter is pressed. I want to hide the dropdown box.

My implementation:

<Select
        ref={ input => this.input = input }
        name="form-field-name"
        searchable
        autoBlur
        clearable={false}
        openOnFocus
        onInputKeyDown={this.onInputKeyDown.bind(this)}
        value={this.state.selectedOption}
        onChange={this.handleChange.bind(this)}
        options={this.props.items}
/>

using onInputKeyDown I am detecting enter keycode. What do I do to remove the dropdown there when 'No results found' is shown?

onInputKeyDown(e) {
    if (e.keyCode === keys.ENTER) {            
        console.log('on input key down');
        // How to detect 'No results found' shown?
        // And then, how to close the dropdown?
    }
}

Answer

Marco Kerwitz picture Marco Kerwitz · Sep 16, 2018

In V2 you can achieve this by setting noOptionsMessage to a function that returns null:

<Select noOptionsMessage={() => null}/>

This will prevent the fallback option from displaying completely. Note that setting noOptionsMessage to null directly will result in an error, the expected prop type here is a function.