iamjpcbau
iamjpcbau

Reputation: 404

React.js: Onblur event fires every key press

I have an onBlur event which should fire an API upon call

However, my problem is the onBlur event gets fired every keypress

I was expecting onBlur to fire only when the user changes field or loses focus on that field

const handleOnBlur = useCallback(() => {
    console.log("ChangePasswordPage - handleOnBlur oldPassword >>> ", oldPassword)
    PasswordService.validateOldPassword(oldPassword)
  });

return (
<input type="text" id="oldPassword" name="oldPassword" className="form-control" 
                value={oldPassword} maxLength="20" 
                onChange={e => setOldPassword(e.target.value)}
                onBlur={ handleOnBlur() }    
            />
)

Also, what's the difference if I trigger the event on useEffect hook? Seems like useEffect also works like onkeypress or every time that certain state is changed

TIA

Upvotes: 2

Views: 3205

Answers (2)

Puja Srivastava
Puja Srivastava

Reputation: 336

On blur will be called everytime you are redering the component, since you are doing onBlur={ handleOnBlur() } , this syntax will lead handleOnBlur function to be called everytime. Since , it is a function call.

Here you need callback, So it should be , onBlur={ () => handleOnBlur() } or onBlur={ handleOnBlur }

So you're having problem of handleOnBlur getting called on every keypress.

Try this,

  const handleOnBlur = () => {
        console.log("ChangePasswordPage - handleOnBlur oldPassword >>> ", oldPassword)
        PasswordService.validateOldPassword(oldPassword)
   };

return (
<input type="text" id="oldPassword" name="oldPassword" className="form-control" 
                value={oldPassword} maxLength="20" 
                onChange={e => setOldPassword(e.target.value)}
                onBlur={ () => handleOnBlur() }  {/* this is how you should call a callback function */}     
            />
)

Upvotes: 6

HermitCrab
HermitCrab

Reputation: 3274

Very simple, just replace:

onBlur={ handleOnBlur() }

with:

onBlur={ handleOnBlur }

Basically, onBlur must point to a function, not to the result of a function

Upvotes: 1

Related Questions