Home > Blockchain >  Switching focus to the next input field in React
Switching focus to the next input field in React

Time:08-24

In my react application, there is a part with entering the verification code. It looks like this: enter image description here

I want the focus to automatically switch to the next digit input field when entering the next digit. Right now I'm using DOM manipulation, but I want to find a more powerful solution.

my code right now: https://codesandbox.io/s/fast-shadow-vqojs2?file=/src/App.js

I saw options for solving problems using Ref. But adding 5 refs is also not very good, in my humble opinion. Please advise something

CodePudding user response:

ref is the solution here

sandbox

Declare ref:

const itemsRef = useRef([]);

Add ref of inputs

<input
  ref={(ref) => itemsRef.current.push(ref)}
  name={`code-${index}`}
  key={index}
  style={{ width: "20px", height: "20px" }}
  onChange={(event) => codeChangeHandler(event)}
  maxLength={1}
/>

Focus next ref:

itemsRef.current[fieldIntIndex   1].focus();

CodePudding user response:

For your case, if the inputs are siblings, you can easily check if there are nextElementSibling for the current input, if YES, then focus on it, if NOT ( the last input in the list ), then blur

const codeChangeHandler = (event) => {
    const element = event.target;
    const nextSibling = element.nextElementSibling;
    nextSibling ? nextSibling.focus() : element.blur();
};

This is a working example

  • Related