Skip to content

onChange called with null when esc pressed #719

@TLadd

Description

@TLadd
  • downshift version: 3.2.10
  • node version: 10.16.0
  • npm (or yarn) version: 1.16.0

Relevant code or config

import React from "react";
import ReactDOM from "react-dom";
import Downshift from "downshift";

import "./styles.css";

function App() {
  const [value, setValue] = React.useState("great");
  const items = [
    { label: "great", value: "great" },
    { label: "bad", value: "bad" }
  ];
  const selectedItem = items.find(item => item.value === value);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Downshift
        items={items}
        itemToString={i => (!i || i.label == null ? "" : String(i.label))}
        selectedItem={selectedItem}
        onChange={item => {
          console.log(item.value);
          setValue(item.value);
        }}
      >
        {({
          getToggleButtonProps,
          getMenuProps,
          getItemProps,
          isOpen,
          selectedItem,
          highlightedIndex
        }) => (
          <div>
            <button {...getToggleButtonProps({})}>
              {(selectedItem && selectedItem.label) || "Select An Item"}
            </button>
            <ul hidden={!isOpen} {...getMenuProps()}>
              {items.map((item, index) => (
                <li
                  {...getItemProps({
                    item,
                    key: item.value,
                    style: {
                      textDecoration:
                        highlightedIndex === index ? "underline" : undefined
                    }
                  })}
                >
                  {item.label}
                </li>
              ))}
            </ul>
          </div>
        )}
      </Downshift>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

What you did:
I created a Downshift dropdown that behaves as a simple select with a button to open/close. I click on the button to open the menu and then press esc key.

What happened:
The onChange prop is called with null, and the above code crashes because onChange is expecting to receive an object.

Reproduction repository:
https://codesandbox.io/s/musing-austin-g1bt1

Problem description:
It was unexpected for me that onChange was triggered at all in this case. I would expect esc to close the menu, but keep the value the same as it was.

Suggested solution:
Do not trigger onChange in this case.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions