How do you manage focus in a React OTP input?
Use useRef to store references to each input: inputsRef.current[index]. To focus the next input: inputsRef.current[index + 1].focus(). To focus the previous: inputsRef.current[index - 1].focus().
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in OTP Input Component in React
Use useState for the values array (e.g., ['', '', '', '']). Use useRef for input references (for focus management). Handle onChange (auto-focus next), onKeyDown (backspace to previous), and onPaste (fill multiple). Call onComplete when all inputs are filled.
Use useState with an array: const [values, setValues] = useState(Array(length).fill('')). On change, update the specific index: const newValues = [...values]; newValues[index] = digit; setValues(newValues).
Add onPaste handler. preventDefault, get the pasted text from e.clipboardData.getData('text'), filter to numeric, split into characters, and update the values array starting from the current index. Focus the last filled input.
Still have questions?
Browse all our FAQs or reach out to our support team
