2

I have used react-select for drop-drown feature in my application. I want to capture whether user has pressed the "Enter" button/key. I have done something like this:

render(){
 const props = {
  className: 'search-combobox',
  placeholder: "search something",
  onChange: this._onSelectionChange.bind(this),
  onSelect: this.props.onSelectedItem,
  options: this.state.options(),
  filterOptions: this._filterOptions.bind(this),
  onInputChange: this._onInputChange.bind(this),
  valueKey: 'id',
};

return(
<Select {...props}
  autoFocus={true}
  clearable={true}
  closeOnSelect={true}
  escapeClearsValue={true}
  onBlurResetsInput={false} />);
}

So on _onInputChange method, I tried this._onInputChange.bind(this, event). It didn't work. How to capture event then

2 Answers2

4

Use onKeyDown prop on react-select to capture a key press event

<Select options={options} onKeyDown={onKeyDown} />

And check which key is pressed using event.keyCode (13 is for ENTER)

const onKeyDown = event => {
  if (event.keyCode === 13) {
    // enter has been pressed
  }
};

Working example: https://stackblitz.com/edit/react-stackoverflow-60219803

j3ff
  • 5,719
  • 8
  • 38
  • 51
  • `e.keyCode` is deprecated. You should be using `e.key === 'Enter'` (or `e.code === 'Enter'`) instead. You can check out the values for `e.key` and `e.code`, alongside the older and deprecated properties at https://keyjs.dev. – Danziger Sep 27 '20 at 07:58
0

Above answer will work fine. I have attached link for keycodes incase if you want to change key.

https://keycode.info/

For enter it is 13.

Also bind required event according to below post.

onKeyPress Vs. onKeyUp and onKeyDown

  • 1
    `e.keyCode` is deprecated. You should be using `e.key` or `e.code` instead. Also, there's an alternative tool that will give you more detailed information about the different values and properties: https://keyjs.dev – Danziger Sep 27 '20 at 07:59