1

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

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

thank you, it work perfectly with what i have expected, but what happen when i have more than 2, i mean it can be 20 or 30 inputs because i have been doing an text editor, so i can not make ref for each of them manually, thank you so much
You don't need to write any code to do that. Simply press Tab to focus the next input and Shift+Tab to focus the previous input
but i can not find the method to automatically press tab or shift+tab, the requirement does not accept do it manually
@TamDo I just updated my code and the live example. It should work fine now.
thank you so much, i had a look at it, it will be a perfect example for me to continue my project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.