'react-select How to hide dropdown menu programmatically when 'no results found' is shown?
Github Repo: react-select
After searching in the select box:
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?
}
}
Solution 1:[1]
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.
Solution 2:[2]
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} />
</>
)
}
Solution 3:[3]
Try using the noResultsText
prop. Set it to null
whenever you would want to hide it.
Solution 4:[4]
If you want to hide the menu when no more options are available you can try to override the MenuList
component. This worked for me:
const MenuList = ({ children, ...props }: MenuListProps) => {
return Array.isArray(children) && children?.length > 0 ? (
<components.MenuList {...props}>
{children}
</components.MenuList>
) : null;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marco Kerwitz |
Solution 2 | |
Solution 3 | Manoj Nama |
Solution 4 | jhadis |