OTP code input

A one-time code input split into boxes. Typing advances, Backspace steps back, arrow keys, Home and End move between boxes, and pasting or SMS autofill spreads the whole code. Numeric or alphanumeric, optional visual grouping such as 3 + 3, one group label for screen readers, error and hint text, onComplete, and a hidden input for form submission.

Forms & inputsComponentTailwind v4

Source

"use client";

import {
  Fragment, useId, useRef, useState,
  type ChangeEvent, type ClipboardEvent, type FocusEvent, type KeyboardEvent, type ReactNode,
} from "react";
import { cn } from "@/lib/utils";

export interface OtpInputProps {
  /** Number of boxes. */
  length?: number;
  value?: string;
  defaultValue?: string;
  onChange?: (value: string) => void;
  /** Called once every box is filled. */
  onComplete?: (value: string) => void;
  /** Names the whole group for screen readers. */
  label: ReactNode;
  hideLabel?: boolean;
  hint?: ReactNode;
  error?: ReactNode;
  /** Splits the boxes visually, such as 3 for "123 456". */
  groupSize?: number;
  mode?: "numeric" | "alphanumeric";
  disabled?: boolean;
  autoFocus?: boolean;
  /** Submits the code with a form under this name. */
  name?: string;
  className?: string;
}

export function OtpInput({
  length = 6, value: controlled, defaultValue = "", onChange, onComplete, label, hideLabel, hint, error,
  groupSize, mode = "numeric", disabled, autoFocus, name, className,
}: OtpInputProps) {
  const id = useId();
  const [uncontrolled, setUncontrolled] = useState(() => defaultValue.slice(0, length));
  const value = (controlled ?? uncontrolled).slice(0, length);
  const inputs = useRef<(HTMLInputElement | null)[]>([]);
  // Focus moves inside the same event that changes the value, before React re-renders; read the latest value here.
  const latest = useRef(value);
  latest.current = value;
  const invalid = Boolean(error);
  const accept = mode === "numeric" ? /[0-9]/ : /[0-9a-z]/i;

  function clean(text: string) {
    return Array.from(text).filter((char) => accept.test(char)).join("").toUpperCase();
  }

  function commit(next: string) {
    next = next.slice(0, length);
    if (next === value) return;
    latest.current = next;
    if (controlled === undefined) setUncontrolled(next);
    onChange?.(next);
    if (next.length === length) onComplete?.(next);
  }

  function focusBox(index: number) {
    const target = inputs.current[Math.max(0, Math.min(index, length - 1))];
    target?.focus();
    target?.select();
  }

  // Writes characters starting at a box: one when typing, the whole code when pasting or autofilling.
  function insert(index: number, chars: string) {
    const start = Math.min(index, value.length);
    const next = (value.slice(0, start) + chars + value.slice(start + chars.length)).slice(0, length);
    commit(next);
    focusBox(Math.min(start + chars.length, length - 1));
  }

  function handleChange(index: number, event: ChangeEvent<HTMLInputElement>) {
    const typed = clean(event.target.value);
    if (!typed) return;
    const current = value[index];
    // The browser keeps the old character when the caret sat beside it; keep only the new one.
    const chars = typed.length === 2 && current && typed.includes(current) ? (typed[0] === current ? typed[1] : typed[0]) : typed;
    insert(index, chars);
  }

  function handlePaste(index: number, event: ClipboardEvent<HTMLInputElement>) {
    event.preventDefault();
    const chars = clean(event.clipboardData.getData("text"));
    if (chars) insert(chars.length >= length ? 0 : index, chars);
  }

  function handleKeyDown(index: number, event: KeyboardEvent<HTMLInputElement>) {
    const last = Math.min(value.length, length - 1);
    switch (event.key) {
      case "Backspace": {
        event.preventDefault();
        if (value[index]) {
          commit(value.slice(0, index) + value.slice(index + 1));
          focusBox(index);
        } else if (index > 0) {
          commit(value.slice(0, index - 1) + value.slice(index));
          focusBox(index - 1);
        }
        break;
      }
      case "Delete":
        event.preventDefault();
        commit(value.slice(0, index) + value.slice(index + 1));
        break;
      case "ArrowLeft":
        event.preventDefault();
        focusBox(index - 1);
        break;
      case "ArrowRight":
        event.preventDefault();
        focusBox(Math.min(index + 1, last));
        break;
      case "Home":
        event.preventDefault();
        focusBox(0);
        break;
      case "End":
        event.preventDefault();
        focusBox(last);
        break;
      default:
        // Typing the character a box already holds would not fire change; still advance.
        if (event.key.length === 1 && event.key.toUpperCase() === value[index] && !event.metaKey && !event.ctrlKey) {
          event.preventDefault();
          focusBox(index + 1);
        }
    }
  }

  // Boxes fill left to right: focusing past the first empty box moves to it.
  function handleFocus(index: number, event: FocusEvent<HTMLInputElement>) {
    if (index > latest.current.length) {
      focusBox(latest.current.length);
      return;
    }
    event.target.select();
  }

  const labelId = `${id}-label`;
  const messageId = `${id}-message`;
  const message = error ?? hint;

  return (
    <div className={cn("flex flex-col gap-2", className)}>
      <span id={labelId} className={cn("text-sm font-medium text-foreground", hideLabel && "sr-only")}>{label}</span>
      <div role="group" aria-labelledby={labelId} aria-describedby={message ? messageId : undefined} className="flex items-center gap-1.5 sm:gap-2">
        {Array.from({ length }, (_, index) => (
          <Fragment key={index}>
            {groupSize && index > 0 && index % groupSize === 0 && (
              <span aria-hidden="true" className="mx-0.5 h-0.5 w-2.5 shrink-0 rounded-full bg-muted-foreground/40 sm:mx-1 sm:w-3" />
            )}
            <input
              ref={(node) => { inputs.current[index] = node; }}
              type="text"
              inputMode={mode === "numeric" ? "numeric" : "text"}
              pattern={mode === "numeric" ? "[0-9]*" : undefined}
              autoComplete={index === 0 ? "one-time-code" : "off"}
              autoCapitalize="characters"
              spellCheck={false}
              autoFocus={autoFocus && index === 0}
              disabled={disabled}
              aria-label={`${mode === "numeric" ? "Digit" : "Character"} ${index + 1} of ${length}`}
              aria-invalid={invalid || undefined}
              value={value[index] ?? ""}
              onChange={(event) => handleChange(index, event)}
              onKeyDown={(event) => handleKeyDown(index, event)}
              onPaste={(event) => handlePaste(index, event)}
              onFocus={(event) => handleFocus(index, event)}
              className={cn(
                "h-12 w-10 min-w-0 shrink rounded-lg border bg-background text-center text-xl font-semibold tabular-nums text-foreground",
                "shadow-xs shadow-black/[0.03] caret-foreground outline-hidden transition-[border-color,box-shadow] duration-150",
                "selection:bg-transparent focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
                "dark:bg-input/20 sm:h-14 sm:w-12",
                invalid
                  ? "border-destructive/70 focus-visible:border-destructive focus-visible:ring-destructive/20"
                  : value[index]
                    ? "border-foreground/25 focus-visible:border-ring focus-visible:ring-ring/40 dark:border-foreground/30"
                    : "border-input focus-visible:border-ring focus-visible:ring-ring/40",
              )}
            />
          </Fragment>
        ))}
      </div>
      {message && (
        <p id={messageId} className={cn("text-[13px] leading-5", invalid ? "text-destructive" : "text-muted-foreground")}>{message}</p>
      )}
      {name && <input type="hidden" name={name} value={value} />}
    </div>
  );
}