react-select icon indicating copy to clipboard operation
react-select copied to clipboard

How to clear select input programatically while on focus?

Open sAnti09 opened this issue 7 years ago • 9 comments

I am trying to add new options as user types and each option is added when the user types a comma. I'm trying to clear the select input field but no matter what I try, it just won't. I have to click the field again before it disappears. I've tried the ff:

  • stateManager.setState({inputValue: ''})
  • manually changing the value of inputRef to empty string
  • calling force update on stateManager.select

sAnti09 avatar Aug 20 '19 02:08 sAnti09

+1

AndrejGajdos avatar Aug 29 '19 21:08 AndrejGajdos

+1

slavaboiko avatar Sep 26 '19 08:09 slavaboiko

To clear the input field you can return empty string in onInputChange prop.

<Select
    onInputChange={(newInputValue, inputMeta) => {
        if(newInputValue.includes(',')) {
            addNewOption(); // option is added when the user types a comma
            return '';
        }
       return newInputValue;
    } }
/>

Xartok avatar Oct 11 '19 21:10 Xartok

its not working for me. my value is changed to null, undefined or even blank, the select component still has previous value.

viv3kk avatar Apr 28 '20 11:04 viv3kk

@Xartok I came here looking for the addNewOption method, which doesn't seem to exist. Did you make it up for the purposes of your example, or is there a method exposed by the library that allows this?

jcuffe avatar Jun 03 '20 18:06 jcuffe

Returning an empty string onInputChange is not working for me. It still has the previous value as @viv3kk mentioned. Is there any other suggestion we could try?

juweez avatar Jun 08 '20 08:06 juweez

Have you tried using the inputValue prop and making the input value fully controlled? You can receive updates to the input value from onInputChange and update the inputValue accordingly.

Methuselah96 avatar Jun 08 '20 19:06 Methuselah96

@jcuffe It was made up for the purpose of the example.

Xartok avatar Jun 09 '20 11:06 Xartok

Greetings everyone,

The text input can be cleared by making this a controlled input and passing an empty string to the inputValue

Here is a codesandbox demonstrating this with the specification of a comma triggering the addition of a new option value.

There are likely other optimizations that could be made, but this should be sufficient to show the use-case is possible and how to proceed.

I will be closing this issue, but can reopen if there are related issues or concerns.

ebonow avatar Dec 04 '20 20:12 ebonow