event.stopPropagation() after Escape key pressed removed from v2 of react-select

Viewed 613

I notice in the Select.js source file of the react-select component, that this code

event.stopPropagation(); 

which was called in v1 after the Escape key had been processed, has been dropped in v2.

v1: https://github.com/JedWatson/react-select/blob/v1.x/src/Select.js#L492

v2: https://github.com/JedWatson/react-select/blob/master/src/Select.js#L1145

Was this intentional? If so, what is the recommended way in v2 to prevent the escape key closing a dialog (which must be closable by Escape key) that contains the react-select component?

I have figured out how to do it by checking the event in the react-select onKeyDown prop callback, but I'm just wondering if this was removed in favor of some other approach that the developers may have in mind.

1 Answers

You can handle it by yourself using onKeyDown, onMenuClose and onMenuOpen:

const Component = () => {
  const [isMenuOpen, setMenuOpen] = useState(false);

  function handleMenuClose() {
    setMenuOpen(false);
  }

  function handleMenuOpen() {
    setMenuOpen(true);
  }

  function handleKeyDown(e: KeyboardEvent) {
    if (e.key === "Escape" && isMenuOpen) {
      e.stopPropagation();
    }
  }

  return (
    <Select
      onKeyDown={handleKeyDown}
      onMenuClose={handleMenuClose}
      onMenuOpen={handleMenuOpen}
      options={[
        { label: "A", value: "A" },
        { label: "B", value: "B" },
        { label: "C", value: "C" },
        { label: "D", value: "D" },
        { label: "E", value: "E" }
      ]}
    />
  );
}

I created a working example with a Modal on CodeSandbox.

Related