I have input box like this,
I want to finish editing by pushing enter key or blur the input .
<input
ref={titleEditBox} type="text" onBlur={blurEditBox}
onKeyDown={keyDownFinishEdit}></input>
const blurEditBox = () =>{
finishEditbox();
}
const keyDownFinishEdit = (e) =>{
if (e.keyCode == 13){
finishEditText();
}
e.stopPropagation();
}
However when i push the return key it calles the keyDownFinishEdit
and then onBlur
so finishEditText()
is called twice.
So my idea is calling , unfocus from keyDownFinishEdit.
Is it possible or is there any good idea to sort out this?
2
Answers
You already figured it out, you can just call
blur
on press enter:You can prevent the double call by stopping the
onBlur
from firing when the Enter key is pressed. Here’s an updated solution:Alternative method
Another method is to use
blur
itself, having it simplicity (it directly triggers the blur event when the Enter key is pressed, which is easy to implement) and no need for flags.However it may suffer of interference from and with other logic in the app and causing the input to lose focus (which triggers the
onBlur
handler) when the Enter key is pressed, which I don’t know it is what you want.