Search code examples
reactjsinputkeyboardfrontendsimulate

ReactJS automatically simulate keyboard


some one help me please, in the codesandbox link here codesandboxlink you can see 2 input type of text, i want in the second input, when you focus and press key "backspace" the cursor pointer will automatically focus on the first input, thank for helping me out, hope you have a good day


Solution

  • What you need to do is to listen to the onKeyDown event. When the event fires, it passes the KeyboardEvent argument that you can use to inspect what key is pressed and other relevant infos. In this case you will need to look for the KeyboardEvent.keyCode. Logging the keycode when you type will reveal the keyCode of the key you just pressed.

    <input
      type="text"
      onKeyDown={(e) => {
        console.log('pressing', e.keyCode)
        }
      }}
    />
    

    After that, you need get the reference of the input to be able to focus the input conditionally.

    export default function Demo() {
      const onKeyDown = (e) => {
        const BACKSPACE_KEY = 8;
        const ENTER_KEY = 13;
        const form = e.target.form;
        const index = Array.prototype.indexOf.call(form, e.target);
    
        let el;
        if (e.keyCode === ENTER_KEY) {
          el = form.elements[index + 1];
        } else if (e.keyCode === BACKSPACE_KEY) {
          el = form.elements[index - 1];
        }
        if (el) el.focus();
    
        e.preventDefault();
      };
    
      return (
        <form>
          <input type="text" onKeyDown={onKeyDown} />
          <input type="text" onKeyDown={onKeyDown} />
          <input type="text" onKeyDown={onKeyDown} />
          <input type="text" onKeyDown={onKeyDown} />
          <input type="text" onKeyDown={onKeyDown} />
        </form>
      );
    }
    

    Live Example

    Edit react-automatically-simulate-keyboard (forked)