React-select: [v2] Backspace on single select results in [] rather than {}

Created on 6 Jun 2018  路  6Comments  路  Source: JedWatson/react-select

Are you reporting a bug or runtime error?

Bug. To reproduce, you can use the link below. Note: This is NOT in isMulti mode. [] makes sense for isMulti.
Code Sandbox

  1. Select a value.
  2. Click on the select to expand the options menu.
  3. While the menu is still open, hit backspace.
  4. Actual: onChange is called with []
  5. Expected: onChange is called with {}

This seems to be an issue that has happened in the past.

Let me know if I can provide any other details. The code sandbox above is simply one of your examples, but with an added console.log call from onChange, nothing else.

All 6 comments

Also ran into this 馃檪 Solved for now with a wrapping onChangeHandler:

  onChangeHandler = (value, actionMeta) => {
    if (this.props.onChange) {
      // fix react-select returning [] on clear
      if (Array.isArray(value) && value.length === 0) {
        this.props.onChange({}, actionMeta);
      } else {
        this.props.onChange(value, actionMeta);
      }
    }
  };

Just ran into this one today. Definitely doesn't make sense to return an empty array if it's a single select. The item or null is what makes sense to return IMO.

https://github.com/JedWatson/react-select/blob/18219f5271705ef150ad16177db43f0c44f0413d/src/Select.js#L802-L810

single select, by default, IS NOT clearable, but backspaceRemovesValue by default is true, so single select can be cleaned by backspace, it is very confusing.

There is a PR (https://github.com/JedWatson/react-select/pull/3216) and I've put a temporary corrected version up at github:mWater/react-select#fix_2682_built for anyone else who is blocked by this bug.

Here is a workaround that works with search input and clearable select :

onSelectChange = item => {
    // Prevent backspace in input (item.length === undefined)
    if (item === null || item.length === undefined) {
      // Write your code here
    }
  }

I hope it help someone

Basically if hitting backspace and nothing is actually selected, then why fire onChange in the first place?

Was this page helpful?
0 / 5 - 0 ratings