Six Box OTP Input With Auto Advance and Paste

A phone check card with six digit boxes. Each digit typed moves the caret to the next box, Backspace in an empty box clears the one before it, the arrow keys step left and right, and pasting 482917 into any box spreads it across the row. The button counts how many digits are missing and becomes Verify once the code is whole. On a phone the boxes narrow slightly so all six fit at 360 pixels.

Code

import { useRef, useState, type ClipboardEvent, type KeyboardEvent } from "react";

const LENGTH = 6; // number of digits in the code
const PHONE = "+44 7700 900 182";

export default function SixBoxOtpInput() {
  const [digits, setDigits] = useState<string[]>(["4", "8", "2", "", "", ""]);
  const boxes = useRef<(HTMLInputElement | null)[]>([]);
  const code = digits.join("");
  const done = code.length === LENGTH;

  const focusAt = (i: number) => boxes.current[Math.max(0, Math.min(LENGTH - 1, i))]?.focus();
  const setAt = (i: number, v: string) => setDigits((d) => d.map((x, j) => (j === i ? v : x)));

  const onInput = (i: number, raw: string) => {
    const only = raw.replace(/\D/g, "");
    if (only.length > 1) return fill(i, only); // autofill can drop a whole code into one box
    setAt(i, only);
    if (only) focusAt(i + 1);
  };
  const fill = (start: number, text: string) => {
    const next = [...digits];
    text.split("").slice(0, LENGTH - start).forEach((c, k) => { next[start + k] = c; });
    setDigits(next);
    focusAt(start + text.length);
  };
  const onKey = (i: number, e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Backspace" && !digits[i]) { e.preventDefault(); setAt(i - 1, ""); focusAt(i - 1); }
    else if (e.key === "ArrowLeft") { e.preventDefault(); focusAt(i - 1); }
    else if (e.key === "ArrowRight") { e.preventDefault(); focusAt(i + 1); }
  };
  const onPaste = (i: number, e: ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    fill(i, e.clipboardData.getData("text").replace(/\D/g, ""));
  };

  return (
    <section className="bg-gradient-to-b from-indigo-50 to-white px-4 py-16 sm:py-20">
      <form onSubmit={(e) => e.preventDefault()} className="mx-auto max-w-md rounded-2xl border border-indigo-100 bg-white p-6 text-center shadow-[0_20px_50px_-24px_rgba(67,56,202,0.35)] sm:p-8">
        <div className="mx-auto grid h-12 w-12 place-items-center rounded-xl bg-indigo-600 text-white" aria-hidden="true">
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="6" y="2" width="12" height="20" rx="2.5" /><path d="M10.5 18h3" /></svg>
        </div>
        <h2 className="mt-4 text-xl font-semibold tracking-tight text-slate-900">Check your phone</h2>
        <p className="mt-1 text-sm text-slate-600">We sent a 6-digit code to <span className="font-medium text-slate-800">{PHONE}</span></p>
        <fieldset className="mt-6">
          <legend className="sr-only">Verification code</legend>
          <div className="flex justify-center gap-2 sm:gap-3">
            {digits.map((d, i) => (
              <input
                key={i}
                ref={(el) => { boxes.current[i] = el; }}
                value={d}
                onChange={(e) => onInput(i, e.target.value)}
                onKeyDown={(e) => onKey(i, e)}
                onPaste={(e) => onPaste(i, e)}
                onFocus={(e) => e.target.select()}
                inputMode="numeric"
                autoComplete={i === 0 ? "one-time-code" : "off"}
                pattern="[0-9]*"
                maxLength={LENGTH}
                aria-label={`Digit ${i + 1} of ${LENGTH}`}
                className={`h-14 w-11 rounded-xl border text-center text-2xl font-semibold tabular-nums text-slate-900 caret-indigo-600 transition-colors focus:border-indigo-600 focus:outline-none focus:ring-4 focus:ring-indigo-100 sm:w-12 ${d ? "border-slate-400 bg-white" : "border-slate-300 bg-slate-50"}`}
              />
            ))}
          </div>
        </fieldset>
        <button type="submit" disabled={!done} className="mt-6 h-11 w-full rounded-xl bg-indigo-600 text-sm font-semibold text-white hover:bg-indigo-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:ring-offset-2 disabled:bg-indigo-200 disabled:text-indigo-900">
          {done ? "Verify" : `Enter ${LENGTH - code.length} more ${LENGTH - code.length === 1 ? "digit" : "digits"}`}
        </button>
        <p className="mt-4 text-sm text-slate-600">Didn&rsquo;t get it? <a href="#" className="rounded font-medium text-indigo-700 underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-600">Send a new code</a></p>
        <p aria-live="polite" className="sr-only">{done ? "All six digits entered" : ""}</p>
      </form>
    </section>
  );
}

Install with one command: npx shadcn@latest add https://we.inc/r/six-box-otp-input-with-auto-advance-and-paste.json

When to use it

  • A login, signup or payment step sends a six-digit code by text message or email.
  • You want the familiar boxed layout people already know from banking and delivery apps.
  • Codes are often copied from another app, so paste has to fill the whole row in one go.
  • The form should post a single code value even though it shows six separate fields.

How to customize it

  • Change `LENGTH` for four or eight digit codes; the plain version follows however many `.sbox-digit` inputs you write.
  • Swap the indigo through `bg-indigo-600`, `focus:border-indigo-600` and `caret-indigo-600`, or `--sbox-accent` in the CSS.
  • Allow letters for alphanumeric codes by changing the `\D` pattern to `[^0-9a-z]` with the i flag and removing `inputMode="numeric"`.
  • Make the boxes larger with `h-14 w-11` to `h-16 w-14` on roomy layouts, keeping the text size in step.

Accessibility

  • The six boxes sit in a fieldset with a hidden legend, and each one is labelled Digit 1 of 6 and so on, so position is clear without seeing the row.
  • The first box carries autocomplete one-time-code, which lets phones offer the code from a message above the keyboard.
  • A polite live region confirms when every digit is in, and the submit button text says how many are still missing.

Questions

Why does every box allow up to six characters?

Autofill and some keyboards insert the full code into the focused box in one event. A maxLength of one would cut that to a single digit, so each box accepts the longer value and the input handler spreads it across the row.

How do I submit the code to my server?

Join the digits array into one string in React and send it in your submit handler. The plain version keeps a hidden input named code updated on every change, so a normal form post includes it.

Can I submit automatically when the sixth digit is typed?

Yes. In React, watch `code` in an effect and call your verify function when its length reaches `LENGTH`. Keep the button anyway so people who paste a wrong code can try again without retyping.

Why select the box contents on focus?

When someone clicks back into a filled box to correct it, the old digit is selected, so typing replaces it rather than adding a second character that the handler would then have to sort out.

Does this work with screen readers?

Each box announces its position and current digit. Because focus moves automatically, the reader follows along box by box, and the fieldset legend tells people what the group of fields is for.

Related: OTP Input Collection with SMS Autofill, Paste and a Resend Timer in React and HTML, Grouped OTP Input With Separator and Resend Timer, OTP Input With Shake Error and Success States.

More inputs or all free UI components. Build your site free to have a full site built around it.

More in Inputs

Product

Who It's For

Features

Resources

Company

View Sitemap