skip to Main Content

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


  1. You already figured it out, you can just call blur on press enter:

    const handleKeyDown = (event) => {
      if (event.key === "Enter") event.target.blur();
      ...
    };
    
    Login or Signup to reply.
  2. You can prevent the double call by stopping the onBlur from firing when the Enter key is pressed. Here’s an updated solution:

    <input 
      ref={titleEditBox} 
      type="text" 
      onBlur={blurEditBox} 
      onKeyDown={keyDownFinishEdit} 
    />
    
    const blurEditBox = () => {
        finishEditBox();
    }
    
    const keyDownFinishEdit = (e) => {
        if (e.keyCode === 13) {  
            e.preventDefault(); // This prevent blur from firing
            finishEditBox();
        }
    }
    

    Alternative method

    if (e.keyCode === 13) {  
        e.target.blur();
        return;
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search