Home > Back-end >  How to dynamically check if input is empty without using onChange?
How to dynamically check if input is empty without using onChange?

Time:01-31

I want to get one-time information from the input control when value is empty and when value is not empty

Right now I'm using onChange like below:

<Input onChange={onChangeValue()} />

But this onChangeValue method is running every time when I type into the input, but I want two times information, first when value from input is empty and second when value from input is not empty.

Can someoone tell me what can I do this?

CodePudding user response:

You can put some logic before your onChangeValue() function that checks the input value's length and then calls onChangeValue():

beforeOnChangeValue = function() {
  if(arguments[0].target.value.length <= 1) return onChangeValue(arguments)
}
<Input onChange={beforeOnChangeValue} />

This way the onChangeValue() function will only be called when the input is either emptied or when the first character is put in

CodePudding user response:

it seems like you're using controlled components (changing the value of the control on every key typing). I think based on your strategy that you could use a flag in the onChange handler like this

  function onChange (evt) {
    setIsEmpty(!!evt.target.value);
    // Your code ...
  }

Then you'll always know if the input is empty or not.

   function Form () {
     const [isEmpty, setIsEmpty] = React.useState(false);
     
      // onChange here

      return <Input className={isEmpty ? 'empty-class' : 'non-empty-class'} />
   }
  •  Tags:  
  • Related