Skip to content
Molecules

OTP input

Boxes for a one-time code, paste fills all.

Variants

2 more takes on the otp input, each a single file you install on its own by its id.

aui-041Split code

A code split into two groups.

$ pnpm dlx asta-ui@latest add otp-input-aui-041

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/otp-input-aui-041.json

aui-042Dark verify

A dark verify card with a resend timer.

$ pnpm dlx asta-ui@latest add otp-input-aui-042

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/otp-input-aui-042.json

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add otp-input

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/otp-input.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/otp-input and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { OtpInput } from "asta-ui/otp-input";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { Fragment, useId, useState, type ClipboardEvent, type SyntheticEvent } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    const KEYFRAMES = `@keyframes asta-otp-drop { from { opacity: 0; transform: translateY(-7px) scale(.9) } }
    @keyframes asta-otp-caret { 0%, 100% { opacity: 1 } 50% { opacity: 0 } }
    @keyframes asta-otp-wave-0 { 0%, 100% { transform: translateY(0) } 35% { transform: translateY(-7px) } }
    @keyframes asta-otp-wave-1 { 0%, 100% { transform: translateY(0) } 35% { transform: translateY(-7px) } }
    @keyframes asta-otp-shake-0 { 0%, 100% { transform: translateX(0) } 20% { transform: translateX(-7px) } 40% { transform: translateX(6px) } 60% { transform: translateX(-4px) } 80% { transform: translateX(2px) } }
    @keyframes asta-otp-shake-1 { 0%, 100% { transform: translateX(0) } 20% { transform: translateX(-7px) } 40% { transform: translateX(6px) } 60% { transform: translateX(-4px) } 80% { transform: translateX(2px) } }`;
    
    // Two copies of each keyframe: switching the name restarts the animation without remounting the boxes
    // (a remount would replay every digit's drop-in too).
    const EASE = "cubic-bezier(.16,1,.3,1)";
    
    export interface OtpInputProps {
      /** Number of boxes. */
      length?: number;
      value?: string;
      defaultValue?: string;
      onChange?: (value: string) => void;
      /** Called once every box is filled. */
      onComplete?: (code: string) => void;
      /** Accept digits only (default). Off allows letters too, upper-cased. */
      digitsOnly?: boolean;
      /** Mark the code as wrong. The boxes shake each time this turns true. */
      error?: boolean;
      disabled?: boolean;
      autoFocus?: boolean;
      /** Put a small dash after every N boxes, e.g. 3 for "123–456". */
      groupSize?: number;
      /** Accessible name. */
      label?: string;
      name?: string;
      className?: string;
    }
    
    /**
     * A one-time code input. One real input sits over the boxes, so typing, Backspace, paste and the phone's
     * SMS autofill all just work. Digits drop in, the active box blinks a caret, a full code makes the boxes
     * wave, and `error` shakes them once.
     */
    export function OtpInput({
      length = 6,
      value,
      defaultValue = "",
      onChange,
      onComplete,
      digitsOnly = true,
      error,
      disabled,
      autoFocus,
      groupSize,
      label = "One-time code",
      name = "code",
      className,
    }: OtpInputProps) {
      const id = useId();
      const [inner, setInner] = useState(defaultValue);
      const code = (value ?? inner).slice(0, length);
      const [focused, setFocused] = useState(false);
      const [wave, setWave] = useState(0);
      const [shake, setShake] = useState(0);
      const [prevError, setPrevError] = useState(Boolean(error));
    
      if (Boolean(error) !== prevError) {
        setPrevError(Boolean(error));
        if (error) setShake((s) => s + 1);
      }
    
      const clean = (s: string) => (digitsOnly ? s.replace(/\D/g, "") : s.replace(/[^a-z0-9]/gi, "").toUpperCase()).slice(0, length);
    
      const update = (raw: string) => {
        const next = clean(raw);
        if (next === code) return;
        if (value === undefined) setInner(next);
        onChange?.(next);
        if (next.length === length && code.length < length) {
          setWave((w) => w + 1);
          onComplete?.(next);
        }
      };
    
      // Paste replaces the whole code, wherever the caret was.
      const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
        e.preventDefault();
        update(e.clipboardData.getData("text"));
      };
    
      // Keep the caret at the end so typing appends and Backspace removes the last box.
      const toEnd = (e: SyntheticEvent<HTMLInputElement>) => {
        const el = e.currentTarget;
        const n = el.value.length;
        if (el.selectionStart !== n || el.selectionEnd !== n) el.setSelectionRange(n, n);
      };
    
      const active = focused ? Math.min(code.length, length - 1) : -1;
      const full = code.length === length;
    
      return (
        <div className={cx("relative inline-flex", disabled && "opacity-45", className)}>
          <style href="asta-otp-input" precedence="asta">{KEYFRAMES}</style>
          <div
            aria-hidden
            className="flex items-center gap-2 motion-reduce:!animate-none"
            style={shake > 0 ? { animation: `asta-otp-shake-${shake % 2} .42s ${EASE} both` } : undefined}
          >
            {Array.from({ length }, (_, i) => {
              const ch = code[i];
              const on = i === active && !error;
              const ring = error
                ? "shadow-[inset_0_0_0_1.5px_var(--color-ink)]"
                : on
                  ? "shadow-[inset_0_0_0_1.5px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_16%,transparent)]"
                  : full
                    ? "shadow-[inset_0_0_0_1.5px_color-mix(in_srgb,var(--color-brand)_55%,transparent)]"
                    : ch
                      ? "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_26%,transparent)]"
                      : "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)]";
              return (
                <Fragment key={i}>
                  {groupSize && i > 0 && i % groupSize === 0 && <span className="mx-0.5 h-[2px] w-2.5 rounded-full bg-[color-mix(in_srgb,var(--color-ink)_22%,transparent)]" />}
                  <span
                    className="block motion-reduce:!animate-none"
                    style={wave > 0 ? { animation: `asta-otp-wave-${wave % 2} .55s ${EASE} ${i * 45}ms both` } : undefined}
                  >
                    <span
                      className={cx(
                        "grid h-12 w-10 place-items-center rounded-[10px] bg-paper text-[22px] font-medium tabular-nums tracking-[-0.02em] transition-shadow duration-200 sm:h-14 sm:w-12 sm:text-[24px]",
                        "text-ink",
                        ring,
                      )}
                    >
                      {ch ? (
                        <span key={`${i}-${ch}`} className="animate-[asta-otp-drop_.3s_cubic-bezier(.16,1,.3,1)_both] motion-reduce:animate-none">
                          {ch}
                        </span>
                      ) : on ? (
                        <span className="h-6 w-[1.5px] rounded-full bg-ink animate-[asta-otp-caret_1.05s_steps(1)_infinite] motion-reduce:animate-none" />
                      ) : null}
                    </span>
                  </span>
                </Fragment>
              );
            })}
          </div>
          <input
            id={id}
            name={name}
            value={code}
            onChange={(e) => update(e.target.value)}
            onPaste={onPaste}
            onFocus={(e) => {
              setFocused(true);
              toEnd(e);
            }}
            onBlur={() => setFocused(false)}
            onSelect={toEnd}
            onClick={toEnd}
            disabled={disabled}
            autoFocus={autoFocus}
            maxLength={length}
            inputMode={digitsOnly ? "numeric" : "text"}
            pattern={digitsOnly ? "[0-9]*" : undefined}
            autoComplete="one-time-code"
            autoCapitalize={digitsOnly ? "none" : "characters"}
            spellCheck={false}
            aria-label={label}
            aria-invalid={error || undefined}
            className="absolute inset-0 h-full w-full cursor-text bg-transparent text-[16px] text-transparent caret-transparent opacity-0 outline-none disabled:cursor-not-allowed"
          />
        </div>
      );
    }
    
    export default OtpInput;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI OTP input component to my project.
    
    Boxes for a one-time code, paste fills all.
    It includes: autofill, paste, caret, complete, error, groups.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add otp-input --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/otp-input.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { OtpInput } from "@/components/astabyte/otp-input";
    ```
    
    Usage example and props: https://ui.astabyte.com/otp-input
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js. On the last digit it fires asta:complete; point hx-post at your verify endpoint. -->
    <div style="display:flex;flex-direction:column;gap:12px;width:100%"><div data-asta-otp class="asta-otp-input"><div aria-hidden="true" data-asta-otp-boxes class="asta-otp-input-boxes"> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:0ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:45ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:90ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span><span class="asta-otp-input-sep"></span> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:135ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:180ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span> <span class="asta-otp-input-wave" data-asta-otp-wave style="--asta-otp-i:225ms;"><span class="asta-otp-input-box" data-asta-otp-box data-state=""></span></span></div><input id="otp" name="code" value="" maxlength="6" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code" spellcheck="false" aria-label="One-time code" class="asta-otp-input-field" hx-post="/verify" hx-trigger="asta:complete"></div><p style="margin:0;font-size:13px;opacity:.7">Enter the 6-digit code Astabyte sent to your email.</p></div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { OtpInput } from "@/components/astabyte/otp-input";

// The "right" code for this demo.
const CODE = "424242";

export default function OtpInputDemo() {
  const [code, setCode] = useState("");
  const [status, setStatus] = useState<"idle" | "wrong" | "ok">("idle");

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col items-center gap-8">
        <div className="flex flex-col items-center gap-2 text-center">
          <span className="grid h-11 w-11 place-items-center rounded-[12px] bg-paper-2 text-ink">
            <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              <rect x="6.5" y="3" width="11" height="18" rx="2" />
              <path d="M11 17.5h2" />
            </svg>
          </span>
          <p className="mt-1 text-[16px] font-medium tracking-[-0.01em] text-ink">Check your phone</p>
          <p className="text-[13px] leading-relaxed text-ink-2">
            We sent a 6-digit code to <span className="tabular-nums text-ink">+1 (415) ••• 0192</span>
          </p>
        </div>

        <OtpInput
          value={code}
          groupSize={3}
          error={status === "wrong"}
          onChange={(v) => {
            setCode(v);
            if (status !== "idle") setStatus("idle");
          }}
          onComplete={(v) => setStatus(v === CODE ? "ok" : "wrong")}
        />

        <p className="h-5 text-[13px]" aria-live="polite">
          {status === "ok" ? (
            <span className="text-brand">Verified. Signing you in…</span>
          ) : status === "wrong" ? (
            <span className="text-ink-2">That code didn&apos;t match. Try again.</span>
          ) : (
            <span className="text-mute">
              Didn&apos;t get it?{" "}
              <button type="button" onClick={() => setCode("")} className="font-medium text-ink underline-offset-2 hover:underline">
                Resend in 0:24
              </button>
            </span>
          )}
        </p>

        <p className="text-center text-[12.5px] text-mute">Type or paste a code. 424242 passes, anything else shakes.</p>
      </div>
    </div>
  );
}