Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
    }
}
like image 364
Sabbiu Shah Avatar asked Mar 22 '18 14:03

Sabbiu Shah


3 Answers

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.

like image 114
Marco Kerwitz Avatar answered Oct 07 '22 01:10

Marco Kerwitz


First method:
Turn off <Menu /> component to hide dropdown list.

    <Select
      components={{
        ...components,
        Menu: () => null
      }}
    />

Second method:
Turn off dropdown conditionally. e.g. When there is no value in input.

// Select.js
import { Menu } from './Menu'
  <Select
    {...props}
    components={{
      Menu
    }}
  />

-------
// Menu.js
import { components } from 'react-select'
export const Menu = props => {
  if (props.selectProps.inputValue.length === 0) return null

  return (
    <>
      <components.Menu {...props} />
    </>
  )
}
like image 44
Aga Avatar answered Oct 07 '22 01:10

Aga


Try using the noResultsText prop. Set it to null whenever you would want to hide it.

like image 44
Manoj Nama Avatar answered Oct 06 '22 23:10

Manoj Nama