Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically close react-select menu

React-select default behavior is to have the menu pop open when the input value is empty. I want to modify this behavior so that when the input is empty, whether before a user has typed anything or the user has backspaced to get to the empty state, the menu will be closed.

I could not find any prop that enables this behavior, so I thought to do it programmatically, by calling some function that closes the menu in onInputChange. Something like:

onInputChange={(inputValue) => {
      this.setState({
        inputValue,
      });
      this.selectRef.closeMenu();
    }}

I tried using blur() on the Select ref but it just blurred the input without closing the menu, definitely not the behavior I'm looking for.

Is there a prop or function that's exposed that can fulfill my needs?

like image 278
stellr42 Avatar asked Aug 25 '26 23:08

stellr42


1 Answers

I kept the open state separately

const [open, setOpen] = useState(false);

<Select
  menuIsOpen={open}
  onMenuOpen={() => setOpen(true)}
  onMenuClose={() => setOpen(false)}
/>

and set false when I want to close it. In this case, like this

onInputChange={(text) => {
  if (text === '') {
    setOpen(false);
  }
}}
like image 123
Sanka Sanjeewa Avatar answered Aug 27 '26 13:08

Sanka Sanjeewa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!