Skip to content
ProLifetime access for $199, paid once, every future release included
Truffle UI

OTP Input

FreeNew

A one-time-code field with animated slots, paste and SMS autofill, and an error shake.

Installation

pnpm dlx shadcn@latest add @viewport/otp-input

First time? Add the @viewport registry to components.json. Setup takes one minute.

Usage

The code behind the preview above.

otp-input-demo.tsx
"use client";

import { useState } from "react";
import { OtpInput } from "@/components/viewport/otp-input";

const CODE = "424242";

export default function OtpInputDemo() {
  const [code, setCode] = useState("");
  const [state, setState] = useState<"idle" | "wrong" | "verified">("idle");

  return (
    <div className="flex flex-col items-center text-center">
      <h3 className="font-semibold tracking-tight">Check your phone</h3>
      <p className="mt-1 text-sm text-muted-foreground">We sent a 6-digit code to the number ending in 42.</p>
      <OtpInput
        aria-label="Verification code"
        className="mt-6"
        groupSize={3}
        value={code}
        invalid={state === "wrong"}
        disabled={state === "verified"}
        onChange={(next) => {
          setCode(next);
          setState("idle");
        }}
        onComplete={(next) => setState(next === CODE ? "verified" : "wrong")}
      />
      <p role="status" className="mt-4 h-5 text-sm">
        {state === "verified" ? (
          <span className="text-emerald-600 dark:text-emerald-400">Verified. You&apos;re in.</span>
        ) : state === "wrong" ? (
          <span className="text-destructive">That code is not right. Try again.</span>
        ) : (
          <span className="text-muted-foreground">
            Try <span className="font-mono text-foreground">{CODE}</span>, or paste it.
          </span>
        )}
      </p>
    </div>
  );
}

Props

PropTypeDefault
lengthnumber

Number of characters in the code.

6
valuestring

Controlled value.

—
defaultValuestring

Initial value when uncontrolled.

""
onChange(value: string) => void—
onComplete(value: string) => void

Called once every slot is filled.

—
alphanumericboolean

Accept letters as well as digits.

false
groupSizenumber

Draw a divider after every this many slots, e.g. 3 for `123-456`.

—
invalidboolean

Marks the code as wrong: red slots and a shake.

false

Accessibility

  • One real input, so screen readers, paste and autocomplete=one-time-code all work.
  • Arrow keys, Home, End and a click move between slots; typing replaces a filled slot.
  • Sets aria-invalid when the code is wrong.
  • The shake and the pop are removed under reduced motion.