OTP Input
FreeNewA 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.
"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'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
| Prop | Type | Default |
|---|---|---|
| length | numberNumber of characters in the code. | 6 |
| value | stringControlled value. | — |
| defaultValue | stringInitial value when uncontrolled. | "" |
| onChange | (value: string) => void | — |
| onComplete | (value: string) => voidCalled once every slot is filled. | — |
| alphanumeric | booleanAccept letters as well as digits. | false |
| groupSize | numberDraw a divider after every this many slots, e.g. 3 for `123-456`. | — |
| invalid | booleanMarks 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.