DEV Community

Cover image for πŸš€ New React Challenge: OTP Input
ReactChallenges
ReactChallenges

Posted on Originally published at reactchallenges.com

πŸš€ New React Challenge: OTP Input

One-time-password inputs look simple until you try to build one. Auto-advancing focus, paste handling, and keyboard navigation all have to work together β€” and that's exactly what this challenge asks you to wire up.


🧩 Overview

Build a six-field OTP input that moves focus as you type, accepts a pasted code, and validates it against a demo code.

πŸ‘‰ https://www.reactchallenges.com/challenges/otp-input


βœ… Requirements

  • Six single-character inputs are rendered, one per digit.
  • The first input is focused on mount.
  • Typing a digit fills the focused input and moves focus to the next input.
  • Non-numeric characters are ignored.
  • Backspace clears the current digit and stays in place.
  • Backspace on an already-empty input clears the previous digit and moves focus to it.
  • ArrowLeft and ArrowRight move focus between inputs.
  • Pasting a code fills the inputs with the pasted digits; digits beyond six are ignored.
  • The status text reads "Waiting for code…" while the code is incomplete.
  • When all six digits are filled and match the demo code, the status reads "Code verified".
  • When all six digits are filled but do not match, the status reads "Invalid code. Try again."
  • The reset button clears all inputs, refocuses the first input, and resets the status.

πŸ’‘ Notes

  • The six inputs are controlled: whatever logic you run in the change handler decides what actually sticks in state, so invalid characters never persist.
  • You need to move focus between inputs imperatively β€” plan how to keep a reference to each field.
  • A single interaction can deliver more than one digit at once (pasting a full code), not just one keypress.
  • Call preventDefault() on the keyboard and paste handlers so the browser doesn't also move the caret or insert text on its own.
  • Prefer deriving the status from the current values instead of storing it as separate state that can drift out of sync.

πŸ§ͺ Tests

  1. renders six inputs
  2. focuses the first input on mount
  3. renders the demo code
  4. types a digit and moves focus to the next input
  5. ignores non-numeric characters
  6. backspace clears the current digit and stays in place
  7. backspace on an empty input clears the previous digit
  8. arrow keys move focus between inputs
  9. pastes the demo code and verifies it
  10. shows an error for a wrong code
  11. truncates extra digits when pasting more than six
  12. reset clears the inputs and refocuses the first

Mastering imperative focus management and derived state in a tiny, familiar UI. That's the skill this challenge leaves you with β€” useful every time you build auth, 2FA, or payment flows.

πŸ”₯ Start the Challenge Now

Top comments (0)