OTP InputLoading saved progress…

OTP Input

Build a one-time-code input as a single React component: six separate single-character boxes, the kind an app shows after texting you a verification code. The interesting part isn't the boxes — it's the focus choreography. Typing a digit fills a box and jumps to the next; backspace walks back; pasting the whole code fans it out across all six. Managing that focus with refs (not DOM queries) is the skill under test.

What you'll build

The starter App.tsx renders six empty boxes and a placeholder line. Make it work:

  1. Hold the digits. Track an array of six characters with useState(Array(6).fill('')).
  2. Keep refs to the boxes. A useRef array of the six inputs lets you focus a sibling.
  3. Type = fill + advance. On change, take the last typed character, ignore non-digits, write it into digits[i], then focus box i + 1.
  4. Backspace = clear or retreat. If the box has a value, clear it; if it is empty, focus box i - 1 and clear that one.
  5. Paste = distribute. On paste, spread the pasted digits one per box and focus the last filled box.
  6. Show the code. Display Code: 123456 once all six are filled, else Code: —.

Examples

  • Focused on box 0, you type 4 — box 0 shows 4 and focus jumps to box 1. Type 2 — box 1 shows 2, focus moves to box 2.
  • Box 3 is empty and focused; you press Backspace — focus moves to box 2 and box 2 is cleared.
  • You paste 123456 into any box — every box fills in order and the last box takes focus. The line reads Code: 123456.

Notes

  • Only digits. Ignore letters and symbols; the boxes accept 09 only.
  • Focus lives on refs. Reach the next box through your ref array, not document.querySelector. That is the whole point.
  • Derive the code. The assembled string is digits.join('') — do not store it as separate state.
  • Styling (dark theme, boxes, focus ring) is already in styles.css; focus on the logic.
Loading editor…
Loading preview…