affectUI › Components › Inputs

OTP Input

The verification code field done right – a gliding focus ring, paste and SMS autofill, a calm shake on errors and a morph into Verified.

Free and open source (MIT). Install: npx shadcn@latest add https://www.affectui.com/r/otp-input.json · Import from @/components/ui/otp-input

When to use

  • Two-step sign-in, email or phone verification, confirming a sensitive action with a one-time code
  • Any short code people copy from an email or SMS – paste and autofill fill every box at once

When not to use

  • Codes longer than about 8 characters or with free-form text – a plain text field is easier to read and correct
  • Passwords or PINs that must stay hidden – the boxes show what's typed

Usage

import { useState } from "react";
import { OtpInput, type OtpStatus } from "@/components/ui/otp-input";

export function VerifyEmail() {
  const [code, setCode] = useState("");
  const [status, setStatus] = useState<OtpStatus>("idle");
  const [triesLeft, setTriesLeft] = useState(3);

  async function verify(value: string) {
    setStatus("verifying");
    const res = await fetch("/api/verify", { method: "POST", body: JSON.stringify({ code: value }) });
    if (res.ok) {
      setStatus("success");
      router.push("/dashboard");
    } else {
      setTriesLeft((n) => n - 1);
      setStatus("error");
    }
  }

  return (
    <OtpInput
      value={code}
      onChange={(next) => {
        setCode(next);
        if (status === "error" && next) setStatus("idle");
      }}
      onComplete={verify}
      status={status}
      errorMessage={`That code didn't work. ${triesLeft} tries left.`}
      separator
      autoFocus
      onResend={() => fetch("/api/send-code", { method: "POST" })}
      resendIn={30}
    />
  );
}

Props

NameTypeDefaultDescription
lengthnumber6Number of boxes
separatorboolean | numberfalseA small dash between the boxes – true puts it in the middle, a number after that many boxes
numericbooleantrueDigits only with the numeric keyboard on phones; false allows letters too, shown in capitals
valuestringThe code – makes the field controlled
defaultValuestring""Starting code when uncontrolled
onChange(code: string) => voidEvery change: typing, Backspace, paste, autofill and the clearing after an error
onComplete(code: string) => voidCalled once the last box is filled by the user – the place to start verifying
status"idle" | "verifying" | "error" | "success""idle"Verifying shimmers and locks the field, error shakes and shows the message, success morphs into the pill
errorMessageReactNode"That code didn't work. Try again."Shown below the boxes after an error, until the user types again
clearOnErrorbooleantrueClears the boxes shortly after the shake, ready for the next try
successLabelstring"Verified"Text in the pill on success
onResend() => voidShows "Didn't get a code?" below the boxes with a countdown that becomes a Resend button; clicking restarts the countdown
resendInnumber30Seconds until the code can be resent
align"start" | "center""start"Where the boxes and the lines below them sit
disabledbooleanfalseDims the field and ignores input
autoFocusbooleanfalseFocuses the field on mount (without scrolling)
labelstring"Verification code"Accessible name; the number of digits is added
classNamestringExtra class on the root

Keyboard

  • 0–9: Fills the active box and moves on; typing on a filled box replaces it
  • ⌫: Clears the box and goes back one
  • ← / →: Moves between the filled boxes and the next empty one
  • Home / End: Jumps to the first box, or to the next empty one
  • ⌘ / V: Pastes a whole code – spaces and dashes are ignored

Accessibility

  • One real text input carries the whole code, so screen readers hear one field ("Verification code, 6 digits") instead of six
  • autocomplete="one-time-code" lets iOS and Android offer the code from an SMS; inputMode="numeric" opens the number pad
  • Errors set aria-invalid and point to the message with aria-describedby; verifying, errors, success and resend are announced in a polite live region

Responsive

  • Container query: the boxes shrink to fit their container – six boxes with a separator fit a 320px phone
  • Inputs use 16px text under the hood, so iOS doesn't zoom in on focus
  • Dark mode built in: switches when an ancestor (usually <html>) has the class dark or data-theme="dark"

Requirements

  • React 19

Related

  • Combobox – Pick one or many from a searchable, grouped list – chips with avatars, highlighted matches, create-on-the-fly and full keyboard support
  • Segmented Control – Switch between two to six options – a raised pill or underline that glides, stretches a little and can be dragged across, with icons, counts and badges
  • Button – Primary, secondary, ghost and destructive buttons with icons, sizes and a shimmering loading state
  • Toaster – Calm toasts from anywhere – a stack that fans out on hover, promise toasts that morph from spinner to check, swipe to dismiss