Answer the question
In order to leave comments, you need to log in
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
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>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question