One-time code input
Six boxes for a verification code that auto-advance, accept a pasted code in one go, and celebrate or shake when the code is checked.
"use client";
import {
useRef,
useState,
type ClipboardEvent,
type KeyboardEvent,
} from "react";
import "./otp-input.css";
type OtpInputProps = {
length?: number;
/** Return true if the code is right. In a real app this calls your server. */
verify?: (code: string) => boolean | Promise<boolean>;
theme?: "light" | "dark";
};
/**
* OtpInput
* - Typing moves forward, Backspace on an empty box moves back, arrows move freely.
* - Pasting a full code fills every box at once.
* - When the last digit is entered the code is verified automatically.
*/
export function OtpInput({
length = 6,
verify = (c) => c === "246810",
theme = "light",
}: OtpInputProps) {
const [digits, setDigits] = useState<string[]>(Array(length).fill(""));
const [state, setState] = useState<"idle" | "checking" | "ok" | "bad">(
"idle",
);
const boxes = useRef<(HTMLInputElement | null)[]>([]);
const commit = async (next: string[]) => {
setDigits(next);
if (next.every(Boolean)) {
setState("checking");
const ok = await verify(next.join(""));
await new Promise((r) => setTimeout(r, 500)); // let the user see "checking"
setState(ok ? "ok" : "bad");
if (!ok) {
setTimeout(() => {
setDigits(Array(length).fill(""));
setState("idle");
boxes.current[0]?.focus();
}, 900);
}
} else if (state !== "idle") setState("idle");
};
const put = (i: number, value: string) => {
const v = value.replace(/\D/g, "");
if (!v) return;
const next = [...digits];
// Typing several digits (some keyboards, autofill) spreads them forward.
v.split("").forEach((d, k) => i + k < length && (next[i + k] = d));
commit(next);
boxes.current[Math.min(i + v.length, length - 1)]?.focus();
};
const onKey = (i: number, e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Backspace") {
e.preventDefault();
const next = [...digits];
if (next[i]) next[i] = "";
else if (i > 0) {
next[i - 1] = "";
boxes.current[i - 1]?.focus();
}
commit(next);
} else if (e.key === "ArrowLeft") boxes.current[i - 1]?.focus();
else if (e.key === "ArrowRight") boxes.current[i + 1]?.focus();
};
const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
put(0, e.clipboardData.getData("text").slice(0, length));
};
const locked = state === "checking" || state === "ok";
return (
<div className="gu-otp" data-theme={theme} data-state={state}>
<p className="gu-otp__title" id="gu-otp-label">
Enter the 6-digit code we sent to •••• 4821
</p>
<div
className="gu-otp__boxes"
role="group"
aria-labelledby="gu-otp-label"
>
{digits.map((d, i) => (
<input
key={i}
ref={(el) => {
boxes.current[i] = el;
}}
value={d}
inputMode="numeric"
autoComplete={i === 0 ? "one-time-code" : "off"}
maxLength={length}
aria-label={`Digit ${i + 1} of ${length}`}
data-filled={d ? "" : undefined}
disabled={locked}
onChange={(e) =>
put(i, e.target.value.slice(d ? 1 : 0) || e.target.value)
}
onKeyDown={(e) => onKey(i, e)}
onPaste={onPaste}
onFocus={(e) => e.currentTarget.select()}
/>
))}
</div>
<p className="gu-otp__status" role="status">
{state === "checking" && "Checking the code…"}
{state === "ok" && "Verified. Welcome back."}
{state === "bad" && "That code didn't match. Try again."}
{state === "idle" && <span>Hint for this demo: 246810</span>}
</p>
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: One-time code input
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A six-box verification code input. Typing advances, Backspace goes back, pasting fills everything, and completing the code verifies automatically with a "checking" wave, then turns green-lime on success or shakes and clears on failure.
## Layout and look
- Title above: "Enter the 6-digit code we sent to •••• 4821".
- Boxes: ~58×70px (scale down on phones), radius 14px, 1.5px border, background #fbf8f2 (dark #18181b), monospace 27px weight 800 digits, orange caret. A wider gap after the third box.
- Focus: blue border (#2b35ff, dark #d7ff3a) and soft ring. Filled: dark border and lifted 3px with a springy transition.
- Success: all boxes lime #d7ff3a with dark digits. Error: orange-red border and digits.
- Status line below.
## Behavior and motion
1. onChange strips non-digits; multiple digits (autofill) spread forward; focus moves to the next empty box.
2. Backspace on an empty box clears and focuses the previous one. Arrow keys move. Focus selects the box content.
3. Paste anywhere fills from the first box.
4. When all boxes are filled: state "checking" (boxes bob in a staggered wave, 80ms per box), then verify. Success locks the inputs. Failure shakes the row (±8px, 450ms), then clears and refocuses the first box after 900ms.
## Touch
inputMode="numeric" and autocomplete="one-time-code" on the first box for SMS autofill.
## Accessibility
- Inputs grouped with role="group" and labelled by the title; each box has "Digit n of 6". Status uses role="status".
- prefers-reduced-motion: no lift, wave or shake.
## Props
length (default 6), verify(code) → boolean | Promise<boolean>, theme.
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### OtpInput.tsx
```tsx
"use client";
import {
useRef,
useState,
type ClipboardEvent,
type KeyboardEvent,
} from "react";
import "./otp-input.css";
type OtpInputProps = {
length?: number;
/** Return true if the code is right. In a real app this calls your server. */
verify?: (code: string) => boolean | Promise<boolean>;
theme?: "light" | "dark";
};
/**
* OtpInput
* - Typing moves forward, Backspace on an empty box moves back, arrows move freely.
* - Pasting a full code fills every box at once.
* - When the last digit is entered the code is verified automatically.
*/
export function OtpInput({
length = 6,
verify = (c) => c === "246810",
theme = "light",
}: OtpInputProps) {
const [digits, setDigits] = useState<string[]>(Array(length).fill(""));
const [state, setState] = useState<"idle" | "checking" | "ok" | "bad">(
"idle",
);
const boxes = useRef<(HTMLInputElement | null)[]>([]);
const commit = async (next: string[]) => {
setDigits(next);
if (next.every(Boolean)) {
setState("checking");
const ok = await verify(next.join(""));
await new Promise((r) => setTimeout(r, 500)); // let the user see "checking"
setState(ok ? "ok" : "bad");
if (!ok) {
setTimeout(() => {
setDigits(Array(length).fill(""));
setState("idle");
boxes.current[0]?.focus();
}, 900);
}
} else if (state !== "idle") setState("idle");
};
const put = (i: number, value: string) => {
const v = value.replace(/\D/g, "");
if (!v) return;
const next = [...digits];
// Typing several digits (some keyboards, autofill) spreads them forward.
v.split("").forEach((d, k) => i + k < length && (next[i + k] = d));
commit(next);
boxes.current[Math.min(i + v.length, length - 1)]?.focus();
};
const onKey = (i: number, e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Backspace") {
e.preventDefault();
const next = [...digits];
if (next[i]) next[i] = "";
else if (i > 0) {
next[i - 1] = "";
boxes.current[i - 1]?.focus();
}
commit(next);
} else if (e.key === "ArrowLeft") boxes.current[i - 1]?.focus();
else if (e.key === "ArrowRight") boxes.current[i + 1]?.focus();
};
const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
put(0, e.clipboardData.getData("text").slice(0, length));
};
const locked = state === "checking" || state === "ok";
return (
<div className="gu-otp" data-theme={theme} data-state={state}>
<p className="gu-otp__title" id="gu-otp-label">
Enter the 6-digit code we sent to •••• 4821
</p>
<div
className="gu-otp__boxes"
role="group"
aria-labelledby="gu-otp-label"
>
{digits.map((d, i) => (
<input
key={i}
ref={(el) => {
boxes.current[i] = el;
}}
value={d}
inputMode="numeric"
autoComplete={i === 0 ? "one-time-code" : "off"}
maxLength={length}
aria-label={`Digit ${i + 1} of ${length}`}
data-filled={d ? "" : undefined}
disabled={locked}
onChange={(e) =>
put(i, e.target.value.slice(d ? 1 : 0) || e.target.value)
}
onKeyDown={(e) => onKey(i, e)}
onPaste={onPaste}
onFocus={(e) => e.currentTarget.select()}
/>
))}
</div>
<p className="gu-otp__status" role="status">
{state === "checking" && "Checking the code…"}
{state === "ok" && "Verified. Welcome back."}
{state === "bad" && "That code didn't match. Try again."}
{state === "idle" && <span>Hint for this demo: 246810</span>}
</p>
</div>
);
}
```
### otp-input.css
```css
/* OtpInput: change these colors to match your brand. */
.gu-otp {
--box: #fbf8f2;
--text: #0e0e10;
--muted: #57534b;
--line: rgb(14 14 16 / 0.18);
--accent: #ff5a1f;
--ok: #d7ff3a;
--bad: #c2410c;
--focus: #2b35ff;
display: grid;
justify-items: center;
gap: 18px;
font-family: system-ui, sans-serif;
color: var(--text);
text-align: center;
}
.gu-otp[data-theme="dark"] {
--box: #18181b;
--text: #f3eee3;
--muted: #aea89c;
--line: rgb(243 238 227 / 0.18);
--bad: #fb923c;
--focus: #d7ff3a;
}
.gu-otp__title {
margin: 0;
font-weight: 700;
}
.gu-otp__boxes {
display: flex;
gap: clamp(6px, 2vw, 12px);
}
.gu-otp input {
width: clamp(42px, 11vw, 58px);
height: clamp(54px, 14vw, 70px);
padding: 0;
border: 1.5px solid var(--line);
border-radius: 14px;
outline: none;
background: var(--box);
color: inherit;
font:
800 1.7rem/1 ui-monospace,
"JetBrains Mono",
monospace;
text-align: center;
caret-color: var(--accent);
transition:
border-color 0.2s,
box-shadow 0.2s,
transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1),
background-color 0.3s;
}
/* A small gap after the third box makes 6 digits easier to read */
.gu-otp input:nth-child(3) {
margin-right: clamp(6px, 2vw, 14px);
}
.gu-otp input:focus {
border-color: var(--focus);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--focus) 20%, transparent);
}
.gu-otp input[data-filled] {
border-color: var(--text);
transform: translateY(-3px);
}
.gu-otp[data-state="checking"] input {
animation: gu-otp-wave 0.9s ease-in-out infinite;
}
.gu-otp[data-state="checking"] input:nth-child(2) {
animation-delay: 0.08s;
}
.gu-otp[data-state="checking"] input:nth-child(3) {
animation-delay: 0.16s;
}
.gu-otp[data-state="checking"] input:nth-child(4) {
animation-delay: 0.24s;
}
.gu-otp[data-state="checking"] input:nth-child(5) {
animation-delay: 0.32s;
}
.gu-otp[data-state="checking"] input:nth-child(6) {
animation-delay: 0.4s;
}
@keyframes gu-otp-wave {
50% {
transform: translateY(-8px);
}
}
.gu-otp[data-state="ok"] input {
border-color: transparent;
background: var(--ok);
color: #0e0e10;
transform: none;
}
.gu-otp[data-state="bad"] input {
border-color: var(--bad);
color: var(--bad);
transform: none;
}
.gu-otp[data-state="bad"] .gu-otp__boxes {
animation: gu-otp-shake 0.45s;
}
@keyframes gu-otp-shake {
20%,
60% {
transform: translateX(-8px);
}
40%,
80% {
transform: translateX(8px);
}
}
.gu-otp__status {
min-height: 1.4em;
margin: 0;
font-size: 0.9rem;
font-weight: 600;
}
.gu-otp__status span {
color: var(--muted);
font-weight: 500;
}
.gu-otp[data-state="bad"] .gu-otp__status {
color: var(--bad);
}
@media (prefers-reduced-motion: reduce) {
.gu-otp input,
.gu-otp input[data-filled] {
transition: none;
transform: none;
}
.gu-otp[data-state="checking"] input,
.gu-otp[data-state="bad"] .gu-otp__boxes {
animation: none;
}
}
```
You might also want
Next piece: Orbit border buttonDate range picker
Components, advanced
Floating label form
Components, beginner
Password strength meter
Components, beginner