Home/Components/Forms/OTP Input - React Animated Verification Code Input
Code · Live Preview
Componenttsx
"use client";

// src/components/OtpInput/OtpInput.tsx
import { AnimatePresence, motion, useAnimationControls, useReducedMotion } from "motion/react";
import { Fragment, useEffect, useRef, useState } from "react";

type Status = "idle" | "loading" | "error" | "success";

type OtpInputProps = {
  /** Number of boxes */
  length?: number;
  /** Controlled value. Leave out to let the component keep its own value */
  value?: string;
  onChange?: (value: string) => void;
  /** Runs when every box is filled */
  onComplete?: (code: string) => void;
  /** "loading" while checking, then "error" or "success" */
  status?: Status;
  /** "numeric" = 0-9 only, "alphanumeric" = letters and numbers */
  type?: "numeric" | "alphanumeric";
  /** Show dots instead of the characters */
  mask?: boolean;
  /** Put a dash after every N boxes, e.g. 3 gives 123-456 */
  groupSize?: number;
  /** Empty the boxes after the error shake */
  clearOnError?: boolean;
  /** Focus color */
  color?: string;
  successColor?: string;
  errorColor?: string;
  autoFocus?: boolean;
  disabled?: boolean;
  /** Read by screen readers */
  label?: string;
  className?: string;
};

export function OtpInput({
  length = 6,
  value,
  onChange,
  onComplete,
  status = "idle",
  type = "numeric",
  mask = false,
  groupSize,
  clearOnError = true,
  color = "#4F46E5",
  successColor = "#16A34A",
  errorColor = "#DC2626",
  autoFocus = false,
  disabled = false,
  label = "Verification code",
  className = "",
}: OtpInputProps) {
  const reduce = useReducedMotion();
  const shake = useAnimationControls();
  const inputRef = useRef<HTMLInputElement>(null);

  const [inner, setInner] = useState("");
  const [focused, setFocused] = useState(false);
  // Changes on each success, to replay the wave
  const [waveKey, setWaveKey] = useState(0);
  // Where the last change started, so pasted characters pop in one by one
  const pasteFrom = useRef(0);

  const val = (value ?? inner).slice(0, length);
  const locked = disabled || status === "loading" || status === "success";

  const update = (next: string) => {
    if (value === undefined) setInner(next);
    onChange?.(next);
  };

  const clean = (raw: string) =>
    (type === "numeric" ? raw.replace(/\D/g, "") : raw.replace(/[^a-z0-9]/gi, "").toUpperCase()).slice(0, length);

  const handleChange = (raw: string) => {
    const next = clean(raw);
    pasteFrom.current = Math.min(val.length, next.length);
    update(next);
    if (next.length === length && val.length !== length) onComplete?.(next);
  };

  // Keep the cursor at the end, so typing always fills the next box
  const keepCaretAtEnd = () => {
    const el = inputRef.current;
    if (el) el.setSelectionRange(el.value.length, el.value.length);
  };

  useEffect(() => {
    if (status === "error") {
      if (!reduce) shake.start({ x: [0, -10, 10, -7, 7, -3, 0], transition: { duration: 0.45 } });
      if (clearOnError) {
        const t = window.setTimeout(() => {
          update("");
          inputRef.current?.focus();
        }, 700);
        return () => clearTimeout(t);
      }
    }
    if (status === "success") setWaveKey((k) => k + 1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status]);

  const accent = status === "error" ? errorColor : status === "success" ? successColor : color;
  // The box waiting for the next character (none when full or showing an error)
  const activeIndex = focused && !locked && status !== "error" && val.length < length ? val.length : -1;

  return (
    <motion.div
      animate={shake}
      className={`relative inline-flex items-center gap-2 sm:gap-3 ${className}`}
      onClick={() => inputRef.current?.focus()}
    >
      {/* One real input covers all the boxes. This keeps paste, SMS autofill,
          and the phone keyboard working, and screen readers see one field */}
      <input
        ref={inputRef}
        value={val}
        onChange={(e) => handleChange(e.target.value)}
        onFocus={() => {
          setFocused(true);
          keepCaretAtEnd();
        }}
        onBlur={() => setFocused(false)}
        onSelect={keepCaretAtEnd}
        onKeyDown={(e) => {
          // Arrow keys would move the cursor between boxes, which we don't use
          if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Home") e.preventDefault();
        }}
        autoFocus={autoFocus}
        disabled={disabled}
        readOnly={status === "loading" || status === "success"}
        maxLength={length}
        inputMode={type === "numeric" ? "numeric" : "text"}
        pattern={type === "numeric" ? "[0-9]*" : "[A-Za-z0-9]*"}
        autoComplete="one-time-code"
        autoCapitalize="characters"
        spellCheck={false}
        aria-label={`${label}, ${length} characters`}
        aria-invalid={status === "error"}
        className="absolute inset-0 z-10 size-full cursor-text text-[16px] text-transparent caret-transparent opacity-0 disabled:cursor-not-allowed"
      />

      {Array.from({ length }, (_, i) => {
        const char = val[i];
        const isActive = i === activeIndex;
        const borderColor =
          status === "error" || status === "success" ? accent : isActive ? color : char ? "rgb(163 163 163 / 0.6)" : "rgb(163 163 163 / 0.35)";

        return (
          <Fragment key={i}>
            {groupSize && i > 0 && i % groupSize === 0 && (
              <span className="h-0.5 w-3 rounded-full bg-neutral-300 dark:bg-neutral-600" aria-hidden="true" />
            )}

            <motion.div
              key={`${i}-${waveKey}`}
              aria-hidden="true"
              className={`relative grid size-11 place-items-center rounded-xl border-2 bg-white text-xl font-semibold text-neutral-900 transition-colors duration-200 sm:size-13 sm:text-2xl dark:bg-neutral-900 dark:text-white ${disabled ? "opacity-50" : ""}`}
              style={{
                borderColor,
                boxShadow: isActive ? `0 0 0 4px color-mix(in srgb, ${color} 18%, transparent)` : "none",
                background:
                  status === "success" || status === "error"
                    ? `color-mix(in srgb, ${accent} 8%, transparent)`
                    : undefined,
              }}
              // Success: a little wave across the boxes. Loading: a soft pulse that travels along
              animate={
                reduce
                  ? {}
                  : status === "success"
                    ? { y: [0, -8, 0] }
                    : status === "loading"
                      ? { opacity: [1, 0.45, 1] }
                      : { y: 0, opacity: 1 }
              }
              transition={
                status === "success"
                  ? { duration: 0.45, delay: i * 0.06, ease: "easeOut" }
                  : status === "loading"
                    ? { duration: 1, delay: i * 0.1, repeat: Infinity, ease: "easeInOut" }
                    : { duration: 0.2 }
              }
            >
              <AnimatePresence mode="popLayout" initial={false}>
                {char && (
                  <motion.span
                    key={char + i}
                    initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10, scale: 0.5 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.6 }}
                    transition={
                      reduce
                        ? { duration: 0.1 }
                        : {
                            type: "spring",
                            stiffness: 500,
                            damping: 25,
                            // Pasted codes fill in one after another
                            delay: Math.max(0, i - pasteFrom.current) * 0.04,
                          }
                    }
                    style={{ color: status === "error" || status === "success" ? accent : undefined }}
                  >
                    {mask ? <span className="block size-2.5 rounded-full bg-current" /> : char}
                  </motion.span>
                )}
              </AnimatePresence>

              {/* Blinking caret in the active box */}
              {isActive && !char && (
                <motion.span
                  className="absolute h-6 w-0.5 rounded-full"
                  style={{ background: color }}
                  animate={reduce ? {} : { opacity: [1, 1, 0, 0] }}
                  transition={{ duration: 1, repeat: Infinity, times: [0, 0.5, 0.5, 1], ease: "linear" }}
                />
              )}
            </motion.div>
          </Fragment>
        );
      })}

      {/* Tells screen readers about checking, errors, and success */}
      <span className="sr-only" role="status" aria-live="polite">
        {status === "loading" ? "Checking code" : status === "error" ? "Wrong code, try again" : status === "success" ? "Code verified" : ""}
      </span>
    </motion.div>
  );
}

export default OtpInput;
// Component Source: https://codekk.dev
DesktopSandpackTailwind v4

Component details

Overview, install command, dependencies, and project links.

An animated OTP and verification code input for React built with TypeScript, Motion, and Tailwind CSS v4. It's made for login, sign up, two-factor authentication, phone and email verification, and invite codes. The boxes look separate, but behind them is one real input. That means pasting a full code, SMS code autofill on phones (autocomplete="one-time-code"), the number keyboard on mobile, and backspace all work the way people expect, and screen readers see one clear field instead of six. As you type, each character pops into its box with a small spring, and the next box gets a colored ring and a blinking caret. When a whole code is pasted, the characters fill in one after another instead of all at once. The status prop shows what happens after the code is checked. During "loading", a soft pulse travels across the boxes and the input is locked. On "error", the row shakes, the boxes turn red, and after a moment they clear so the user can try again. On "success", the boxes turn green and do a little wave, one after another. The onComplete callback runs as soon as every box is filled, so you can check the code right away. The type prop switches between numbers only and letters plus numbers (letters are turned into capitals), mask shows dots instead of characters, and groupSize adds a dash between groups, like 123-456. The length, colors, and label can all be changed, and it works as a controlled or uncontrolled input. Dark mode styles are included. A polite live region tells screen readers when the code is being checked, is wrong, or is verified. When prefers-reduced-motion is enabled, the pop, shake, wave, and blinking are turned off and only colors change. "use client" is included, so it works in Vite, Create React App, and Next.js.

Install

terminal
npm
npm create vite@latest my-app -- --template react-ts cd my-app npm install motion

Dependencies

motion
Added Nov 25, 2026

Discussion

Feedback, implementation tips, and usage notes.

0 threads

Comments

Sign in to join the conversation