newbeeep
newbeeep

Reputation: 625

How to prevent ArrowDown when reached bottom in react-select?

In react-select,

When press ArrowDown on last option, focus is going to first option. And press ArrowUp on first option, focus is going to last option.

How to prevent it? Should I make my own MenuList for this?

I really want to prevent only this behavior because I will fetch more options from server when focus reached last option.

Upvotes: 1

Views: 657

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81520

There is no API in the docs to do such thing I'm afraid. One possible solution is to:

  • Keep track of your current focus index by listening to focus event.
  • Intercept keydown event and stop the keystroke conditionally based on the current focus index and options.length. Note that keydown event fires before focus event.
export function MySelect() {
  const focusIndexRef = useRef(-1);

  return (
    <Select
      options={options}
      ariaLiveMessages={{
        onFocus: (e) => {
          focusIndexRef.current = e.options.indexOf(e.focused);
        }
      }}
      onKeyDown={(e) => {
        if (e.key === "ArrowDown" && focusIndexRef.current === options.length - 1) {
          e.preventDefault();
        }
        if (e.key === "ArrowUp" && focusIndexRef.current === 0) {
          e.preventDefault();
        }
      }}
    />
  );
}

Live Demo

Edit 66962934/how-to-prevent-arrowdown-when-reached-bottom-in-react-select

Upvotes: 2

Related Questions