All questions

Auth Code Input

Premium

Auth Code Input

Build a six-cell auth code (OTP) input: one box per digit, with the keyboard ergonomics people expect — type and it auto-advances, Backspace deletes and steps back, arrow keys move between cells, and pasting a code fills every box at once. The state is a small array of characters; the work is the focus management between cells.

Signature

// A self-contained component. No props.
function App(): JSX.Element;

Six single-character inputs that behave like one code field.

Examples

type "4" in cell 0 → cell 0 = 4, focus jumps to cell 1
Backspace in an empty cell 2 → focus cell 1, clear it
ArrowLeft / ArrowRight → move focus between cells
paste "123456" anywhere → cells become 1 2 3 4 5 6, focus the last

Notes

  • State is an array of chars. code[i] is the digit in cell i; render each input from it.
  • Refs for focus. Keep a ref to each input so handlers can move focus programmatically.
  • Auto-advance / retreat. Typing moves focus forward; Backspace on an empty cell moves it back.
  • Paste fills all. Intercept paste, distribute the digits across cells, focus the last filled one.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium