ComponentsPlays on its own. Click to take over.
Forms & Inputs
OTP Input
A one-time code input for React. Paste, autofill and backspace work, with success and error states.
Check your email
Demo code is 123456. Anything else shows the error.
Enter the code we sent you
Install
Copies the source into components/ui/otp-input.tsx and installs what it needs.
$ pnpm dlx shadcn@latest add https://makeui.xyz/r/otp-input.jsonUsage
app/page.tsx
import { OtpInput } from "@/components/ui/otp-input"
export default function Example() {
return <OtpInput length={6} onComplete={(code) => console.log(code)} />
}Source
Prefer to copy by hand? It's one file. Requires motion and the shadcn cn helper.
components/ui/otp-input.tsx
"use client"
import { useEffect, useRef, useState } from "react"
import { AnimatePresence, motion, useAnimate, useReducedMotion } from "motion/react"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
type Status = "idle" | "verifying" | "success" | "error"
export default function OtpInput({
length = 6,
onComplete,
onResend,
resendAfter = 30,
autoFocus = false,
className,
}: {
length?: number
/** Called once every digit is in. Return false (or throw) to show an error, anything else counts as a success. */
onComplete?: (code: string) => boolean | void | Promise<boolean | void>
onResend?: () => void
/** Seconds before "Resend code" turns on. Use 0 to hide the resend line. */
resendAfter?: number
autoFocus?: boolean
className?: string
}) {
const reduce = useReducedMotion()
const [scope, shake] = useAnimate()
const input = useRef<HTMLInputElement>(null)
const [value, setValue] = useState("")
const [focused, setFocused] = useState(false)
const [status, setStatus] = useState<Status>("idle")
const [wait, setWait] = useState(resendAfter)
const run = useRef(0)
useEffect(() => {
if (wait <= 0) return
const id = setTimeout(() => setWait((w) => w - 1), 1000)
return () => clearTimeout(id)
}, [wait])
const submit = async (code: string) => {
const mine = ++run.current
setStatus("verifying")
const wait500 = new Promise((r) => setTimeout(r, 500))
let ok = true
try {
ok = (await onComplete?.(code)) !== false
} catch {
ok = false
}
await wait500
if (mine !== run.current) return
if (ok) {
setStatus("success")
return
}
setStatus("error")
if (!reduce && scope.current)
shake(scope.current, { x: [0, -9, 9, -6, 6, -3, 0] }, { duration: 0.45 })
setTimeout(() => {
if (mine !== run.current) return
setValue("")
setStatus("idle")
input.current?.focus()
}, 700)
}
const change = (raw: string) => {
if (status === "verifying" || status === "success") return
const next = raw.replace(/\D/g, "").slice(0, length)
setValue(next)
if (next.length === length) void submit(next)
}
const caret = Math.min(value.length, length - 1)
const done = status === "success"
return (
<div className={cn("w-fit", className)}>
<div ref={scope} className="relative">
<div className="flex gap-2" aria-hidden>
{Array.from({ length }, (_, i) => {
const char = value[i]
const isActive = focused && status === "idle" && i === caret
return (
<div
key={i}
className={cn(
"relative grid h-14 w-11 place-items-center rounded-xl border bg-card text-xl font-semibold tabular-nums shadow-sm transition-[border-color,box-shadow,background-color] duration-200",
status === "error" && "border-red-500/70 bg-red-500/5 text-red-600",
done && "border-emerald-500/70 bg-emerald-500/10 text-emerald-600",
status !== "error" &&
!done &&
(isActive
? "border-foreground ring-4 ring-foreground/10"
: "border-border"),
)}
>
<AnimatePresence initial={false}>
{char && (
<motion.span
key={char + i}
initial={
reduce
? false
: { opacity: 0, y: 8, scale: 0.8, filter: "blur(3px)" }
}
animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: 0.8, transition: { duration: 0.08 } }}
transition={{ type: "spring", stiffness: 500, damping: 28 }}
className="absolute"
>
{char}
</motion.span>
)}
</AnimatePresence>
{isActive && !char && (
<span className="h-6 w-px animate-pulse bg-foreground" />
)}
</div>
)
})}
</div>
{/* One real input sits on top, so paste, autofill and the mobile keyboard just work. */}
<input
ref={input}
value={value}
onChange={(e) => change(e.target.value)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
autoFocus={autoFocus}
inputMode="numeric"
autoComplete="one-time-code"
pattern="[0-9]*"
maxLength={length}
aria-label={`${length}-digit code`}
aria-invalid={status === "error"}
className="absolute inset-0 h-full w-full cursor-text bg-transparent text-transparent caret-transparent opacity-0 outline-none"
/>
</div>
<div
className="mt-3 flex h-5 items-center justify-between text-xs"
aria-live="polite"
>
<span
className={cn(
"flex items-center gap-1.5",
status === "error"
? "text-red-500"
: done
? "text-emerald-600"
: "text-muted-foreground",
)}
>
{status === "verifying" && (
<span className="size-3 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-foreground" />
)}
{done && <Check className="size-3.5" strokeWidth={3} />}
{status === "idle" && "Enter the code we sent you"}
{status === "verifying" && "Checking..."}
{status === "error" && "That code is not right. Try again."}
{done && "Verified"}
</span>
{resendAfter > 0 && !done && (
<button
type="button"
disabled={wait > 0}
onClick={() => {
setWait(resendAfter)
onResend?.()
input.current?.focus()
}}
className="cursor-pointer text-muted-foreground underline-offset-2 outline-none enabled:hover:text-foreground enabled:hover:underline focus-visible:underline disabled:cursor-default disabled:no-underline tabular-nums"
>
{wait > 0 ? `Resend in 0:${String(wait).padStart(2, "0")}` : "Resend code"}
</button>
)}
</div>
</div>
)
}