N
N
nikmil2019-10-15 00:24:42
React
nikmil, 2019-10-15 00:24:42

How to pass focus from one input to another in react?

Good night, I have 4 inputs, each input has a maximum of 1 character, I need that when I enter one number into the input, the focus changes to 2 inputs and so on. How to implement it? These inputs are used to enter the verification code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-10-15
@nikmil

function App() {
  const [ values, setValues ] = React.useState(Array(10).fill(''));

  const onChange = e => {
    const index = +e.target.dataset.index;
    const value = e.target.value;

    setValues(values.map((n, i) => i === index ? value : n));

    if (index < values.length - 1 && value) {
      inputRefs[index + 1].focus();
      inputRefs[index + 1].select();
    }
  };

  const inputRefs = [];

  return (
    <div>
      {values.map((n, i) => (
        <div>
          <input
            value={values[i]}
            data-index={i}
            onChange={onChange}
            ref={input => inputRefs[i] = input}
            maxLength="1"
          />
        </div>
      ))}
    </div>
  );
}

https://jsfiddle.net/2e13fmcL/1/

D
Dmitry, 2019-10-15
@dimoff66

When rendering:

<input 
  ref={someConditionIsTrue ? (input) => { this.focusedInput = input } : null} 
  ...        
/>

and
componentDidMount(){
  this.focusedInput && this.focusedInput.focus();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question