Input OTP
A field for a short code sent by email, text message or an authenticator app. It draws one box per character, but it is one real input underneath, so a pasted code, the code a phone suggests and a password manager fill it in one go. For any other short text use the input.
Install
npx shadcn@latest add https://thrumui.dev/r/input-otp.jsonAdds components/ui/input-otp.tsx. Nothing else in your project changes.
import { InputOTP } from "@/components/ui/input-otp";Automatically installs icon minus from the icon set.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
InputOTP: maxLength | number | Default 6 | How many characters the code has. With no children the field draws that many boxes in one group. |
InputOTP: value | string | – | The code so far, when the parent holds it. Use it with onValueChange. |
InputOTP: defaultValue | string | Default "" | The code at first, when the field holds it itself. |
InputOTP: onValueChange | (value: string) => void | – | Called with the new code after every typed, deleted or pasted character. |
InputOTP: onComplete | (value: string) => void | – | Called with the code when the last box is filled. Submit or verify here. |
InputOTP: type | "numeric" | "alphanumeric" | Default "numeric" | numeric takes digits and opens the number pad on a phone. alphanumeric takes letters as well. Anything else typed or pasted is dropped. |
InputOTP: size | "sm" | "md" | "lg" | Default "md" | The boxes are 28, 32 or 40 pixels square. They get narrower when the container is too small for them. |
InputOTP: autoComplete | string | Default "one-time-code" | Lets a phone offer the code from a text message. Set off for a code that is not a sign-in code. |
InputOTP: disabled | boolean | Default false | The boxes are dimmed and the field cannot be focused. |
InputOTP: aria-invalid | boolean | – | Marks the code as wrong: every box's border takes the destructive colour. Pair it with a message linked by aria-describedby. |
InputOTP: sound | boolean | Default true | Play the success sound when the last box is filled, if the visitor has sound on. |
InputOTP: className | string | – | Extra classes for the root that holds the boxes and the input, merged last. |
InputOTP: ...props | ComponentProps<"input"> | – | Every other input attribute and event handler goes to the real input: id, name, required, autoFocus, aria-label. |
InputOTPGroup | ComponentProps<"div"> | – | Boxes that sit together and share their borders. |
InputOTPSlot: index | number | Required | Which character of the code the box shows, counted from 0. |
InputOTPSeparator | ComponentProps<"div"> | – | A dash between two groups. |
Motion and sound
Motion
- The focus ring and the caret move to the next box at once, as a text caret does. The caret does not blink.
- The border colour changes over 150 ms when the code becomes invalid or valid again.
- Reduced motion: the border changes at once.
Sound
- A subtle tick on each entered character and the two-note success sound when the last box is filled, by typing or by a paste.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The field is one native text input laid over the boxes, so a screen reader hears a single text field with the whole code, not six fields.
- Its name comes from a label element linked with htmlFor and id, or from an aria-label. The boxes are a picture of its value and are hidden from screen readers.
- The box that takes the next character carries the focus ring, 2 pixels of the theme's ring colour, and a still caret.
- The caret always sits after the last character: the code is edited from its end, and the arrow keys do not move into it.
- The input's text is 16 pixels, so a phone does not zoom the page when it takes focus.
- At 160 pixels wide the boxes share the width and get narrower. Nothing overflows.
| Keys | Action |
|---|---|
| Tab | Focus the field. It is one tab stop, however many boxes it has. |
| 0 to 9, A to Z | Fill the next box. Characters the type does not allow are ignored, and so is anything typed after the last box. |
| Backspace | Clear the last filled box and step back to it. |
| Ctrl / ⌘ + V | Paste a code. It replaces what is there; spaces and dashes are dropped and the rest fills the boxes from the first. |
Source
"use client";
import { createContext, useContext, useState, type ComponentProps, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { MinusIcon } from "@/components/icons/minus";
export type InputOTPSize = "sm" | "md" | "lg";
/** What the boxes need to draw themselves: the code so far, the box that takes the next character, and the size. */
type Code = { value: string; active: number; size: InputOTPSize };
const CodeContext = createContext<Code>({ value: "", active: -1, size: "md" });
export type InputOTPProps = Omit<ComponentProps<"input">, "value" | "defaultValue" | "onChange" | "size" | "type" | "maxLength" | "pattern" | "children"> & {
/** How many characters the code has. Without children, that many boxes are drawn in one group. */
maxLength?: number;
/** The code so far, when the parent holds it. Use with `onValueChange`. */
value?: string;
/** The code at first, when the field holds it itself. */
defaultValue?: string;
/** Called with the new code after every typed, deleted or pasted character. */
onValueChange?: (value: string) => void;
/** Called with the code when the last box is filled. */
onComplete?: (value: string) => void;
/** `numeric` takes digits and opens the number pad on a phone. `alphanumeric` takes letters too. */
type?: "numeric" | "alphanumeric";
/** Boxes are 28 (`sm`), 32 (`md`) or 40 (`lg`) pixels square. */
size?: InputOTPSize;
/** Play the success sound when the last box is filled, if the visitor has sound on. */
sound?: boolean;
/** The boxes: `InputOTPGroup`, `InputOTPSlot` and `InputOTPSeparator`. */
children?: ReactNode;
};
const SLOT: Record<InputOTPSize, string> = {
sm: "h-7 w-7 text-sm",
md: "h-8 w-8 text-sm",
lg: "h-10 w-10 text-base",
};
/**
* A field for a one-time code, drawn as one box per character. Underneath it is a single text input, so a pasted code,
* the code suggested from a text message and a password manager all fill it in one go. Name it with a `<label>` or an `aria-label`.
*/
export function InputOTP({
maxLength = 6,
value,
defaultValue = "",
onValueChange,
onComplete,
type = "numeric",
size = "md",
sound = true,
className,
children,
autoComplete = "one-time-code",
onFocus,
onBlur,
...props
}: InputOTPProps) {
const [inner, setInner] = useState(defaultValue);
const [focused, setFocused] = useState(false);
// Spaces and dashes in a pasted code are dropped, with anything else that does not belong.
const clean = (text: string) => text.replace(type === "numeric" ? /[^0-9]/g : /[^0-9a-zA-Z]/g, "").slice(0, maxLength);
const code = clean(value ?? inner);
const change = (next: string) => {
if (next === code) return;
setInner(next);
onValueChange?.(next);
if (next.length === maxLength) {
if (sound) play("success");
onComplete?.(next);
} else if (sound && next.length > code.length) {
play("tick");
}
};
// A deliberate limit: the caret always sits after the last character, so the code is edited from its end only.
// Editing in the middle would need a selection model for the boxes. Add one when people ask to fix a digit in place.
const toEnd = (input: HTMLInputElement) => {
const end = input.value.length;
if (input.selectionStart !== end || input.selectionEnd !== end) input.setSelectionRange(end, end);
};
return (
<div data-slot="input-otp" className={cn("group/otp relative inline-flex max-w-full min-w-0 has-disabled:opacity-50", className)}>
{/* The boxes are a picture of the input's value. Screen readers get the input itself. */}
<div aria-hidden="true" className="flex min-w-0 items-center gap-2">
<CodeContext value={{ value: code, active: focused ? Math.min(code.length, maxLength - 1) : -1, size }}>
{children ?? (
<InputOTPGroup>
{Array.from({ length: maxLength }, (_, index) => (
<InputOTPSlot key={index} index={index} />
))}
</InputOTPGroup>
)}
</CodeContext>
</div>
<input
{...props}
data-slot="input-otp-input"
type="text"
inputMode={type === "numeric" ? "numeric" : "text"}
pattern={type === "numeric" ? "[0-9]*" : "[0-9a-zA-Z]*"}
autoComplete={autoComplete}
autoCapitalize="off"
autoCorrect="off"
spellCheck={false}
maxLength={maxLength}
value={code}
onChange={(event) => change(clean(event.target.value))}
onPaste={(event) => {
// A pasted code replaces what is there, and may be longer than the field before it is cleaned.
event.preventDefault();
const pasted = clean(event.clipboardData.getData("text"));
if (pasted) change(pasted);
}}
onSelect={(event) => toEnd(event.currentTarget)}
onFocus={(event) => {
setFocused(true);
toEnd(event.currentTarget);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
// It covers the boxes and is invisible, so a press anywhere focuses it. 16px text keeps a phone from zooming.
className="absolute inset-0 size-full cursor-text text-base opacity-0 disabled:cursor-not-allowed"
/>
</div>
);
}
/** Boxes that sit together, sharing their borders. */
export function InputOTPGroup({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="input-otp-group" className={cn("flex min-w-0 items-center", className)} {...props} />;
}
export type InputOTPSlotProps = ComponentProps<"div"> & {
/** Which character of the code this box shows, counted from 0. */
index: number;
};
/** One box. It shows its character, and a caret while it is the box that takes the next one. */
export function InputOTPSlot({ index, className, ...props }: InputOTPSlotProps) {
const { value, active, size } = useContext(CodeContext);
const character = value[index];
const on = active === index;
return (
<div
data-slot="input-otp-slot"
data-surface="control"
data-active={on || undefined}
className={cn(
// Boxes may shrink below their size, so six of them still fit a 160 pixel container.
"relative flex min-w-0 shrink items-center justify-center border-y border-e border-input bg-background font-medium text-foreground tabular-nums first:rounded-s-md first:border-s last:rounded-e-md dark:border-foreground/25",
"transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
"data-active:z-10 data-active:outline-2 data-active:-outline-offset-1 data-active:outline-ring",
"group-has-aria-invalid/otp:border-destructive",
SLOT[size],
className,
)}
{...props}
>
{character}
{/* The caret stands still: nothing on the page blinks. */}
{on && !character && <span data-slot="input-otp-caret" className="h-4 w-px bg-foreground" />}
</div>
);
}
/** A dash between two groups, as in 123-456. */
export function InputOTPSeparator({ className, ...props }: ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" className={cn("flex-none text-muted-foreground", className)} {...props}>
<MinusIcon size={16} />
</div>
);
}Files and dependencies
- Adds
components/ui/input-otp.tsx- Packages
- None
- Brings along
- Sound engine
- Icons
minus
Changelog
- 1.0.0 · 2026-12-03First release.