Skip to content
Shaken UI
Sign in

Input OTP

Save

A one-time code input with one cell per character, grouped cells, paste support, a busy state, and a caret that respects reduced motion.

Category
Forms
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Input OTP preview

Enter the 6-digit code we sent to ada@northwind.dev. Try 482916.

Use one of the backup codes you saved when you turned on two-factor sign-in.

Installation

npx @shakenui/cli add input-otp

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add input-otp --dry-run

Usage

input-otp-example.tsx
"use client";

import { useState } from "react";
import { InputOTP } from "@/components/shaken/ui/input-otp";

export default function InputOTPExample() {
  const [status, setStatus] = useState<"idle" | "checking" | "wrong" | "verified">("idle");

  function verify(code: string) {
    setStatus("checking");
    window.setTimeout(() => setStatus(code === "482916" ? "verified" : "wrong"), 900);
  }

  return (
    <div className="grid w-full max-w-sm gap-8">
      <InputOTP
        label="Verification code"
        groups={[3, 3]}
        autoComplete="one-time-code"
        busy={status === "checking"}
        readOnly={status === "checking" || status === "verified"}
        onValueChange={() => status === "wrong" && setStatus("idle")}
        onValueComplete={verify}
        description={
          status === "verified" ? (
            <span className="text-emerald-600 dark:text-emerald-400">Verified. You can close this tab.</span>
          ) : (
            "Enter the 6-digit code we sent to ada@northwind.dev. Try 482916."
          )
        }
        error={status === "wrong" ? "That code did not match. Check the latest email." : undefined}
      />
      <InputOTP
        label="Recovery code"
        length={8}
        groups={[4, 4]}
        validationType="alphanumeric"
        normalizeValue={(value) => value.toUpperCase()}
        description="Use one of the backup codes you saved when you turned on two-factor sign-in."
      />
    </div>
  );
}

API

PropTypeDefaultDescription
lengthnumber6Number of characters.
groupsnumber[]—How the cells split, for example [3, 3]; a dash separates groups.
value / defaultValuestring—The code.
onValueChange(value: string) => void—Called on every change.
onValueComplete(value: string) => void—Called when the last cell is filled or a full code is pasted.
validationType"numeric" | "alpha" | "alphanumeric" | "none""numeric"Which characters are accepted.
label / description / errorReactNode—Like Input: a bound label, helper text, and an error that marks the cells invalid.
busybooleanfalseShows a spinner after the cells and sets aria-busy while the code is checked.

Accessibility

  • The label names the first cell; the other cells are labeled "Character n of length".
  • Typing advances, Backspace steps back, arrow keys move between cells, and a pasted code fills every cell.
  • Helper and error text are linked with aria-describedby; an error sets aria-invalid on the cells.
  • The custom caret blinks only when reduced motion is not preferred, and holds still otherwise.
  • autoComplete="one-time-code" lets phones offer the code from a text message.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/input-otp.tsxinput-otp
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/input-otp/0.1.0.json.

ui/input-otp.tsxShow
ui/input-otp.tsx
"use client";

import { OTPField as BaseOTPField } from "@base-ui/react/otp-field";
import { Fragment, type ReactNode, useEffect, useId, useRef } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

export interface InputOTPProps extends Omit<BaseOTPField.Root.Props, "length" | "children"> {
  /** Number of characters in the code. */
  length?: number;
  /**
   * How the cells are split into groups, for example `[3, 3]` for a six-digit code read in two
   * halves. A short dash separates the groups. Defaults to one group.
   */
  groups?: number[];
  /** Visible label. Pass `aria-label` instead when the label is shown elsewhere. */
  label?: ReactNode;
  /** Helper text below the cells, for example where the code was sent. */
  description?: ReactNode;
  /** Error message. Marks the cells invalid and replaces the description. */
  error?: ReactNode;
  /** Shows a spinner after the cells and sets `aria-busy`, for example while the code is checked. */
  busy?: boolean;
  /** Classes for the wrapping element. `className` styles the row of cells. */
  containerClassName?: string;
}

/**
 * A one-time code entry with one cell per character. Typing moves to the next cell, Backspace
 * steps back, arrow keys move between cells, and pasting a whole code fills every cell at once.
 * The empty focused cell shows a blinking caret; under reduced motion the caret holds still.
 * Use `onValueComplete` to verify the code as soon as the last character lands.
 */
export function InputOTP({
  length = 6,
  groups,
  label,
  description,
  error,
  busy = false,
  id,
  className,
  containerClassName,
  disabled,
  "aria-describedby": describedBy,
  ...props
}: InputOTPProps) {
  const generatedId = useId();
  const inputId = id ?? generatedId;
  const messageId = `${inputId}-message`;
  const invalid = error != null && error !== false;
  const message = invalid ? error : description;
  const sizes = groups?.length ? groups : [length];

  let offset = 0;
  const cells = sizes.map((size, group) => {
    const start = offset;
    offset += size;
    return (
      <Fragment key={group}>
        {group > 0 ? <span aria-hidden="true" className="h-px w-2.5 shrink-0 bg-zinc-300 dark:bg-zinc-700" /> : null}
        <div className="flex min-w-0 gap-1.5">
          {Array.from({ length: size }, (_, i) => (
            <InputOTPSlot key={start + i} index={start + i} length={length} invalid={invalid} />
          ))}
        </div>
      </Fragment>
    );
  });

  return (
    <div className={cx("grid min-w-0 grid-cols-[minmax(0,1fr)] gap-1.5", containerClassName)}>
      {label ? (
        <label htmlFor={inputId} className="text-sm leading-5 font-medium text-zinc-950 dark:text-white">
          {label}
        </label>
      ) : null}
      <div className="flex min-w-0 items-center gap-3">
        <BaseOTPField.Root
          id={inputId}
          length={length}
          disabled={disabled}
          aria-busy={busy || undefined}
          aria-describedby={cx(message ? messageId : null, describedBy) || undefined}
          className={withBase("flex min-w-0 items-center gap-2 data-[disabled]:opacity-60", className)}
          {...props}
        >
          {cells}
        </BaseOTPField.Root>
        {busy ? (
          <svg
            aria-hidden="true"
            viewBox="0 0 16 16"
            fill="none"
            className="size-4 shrink-0 text-zinc-400 motion-safe:animate-spin starting:opacity-0 transition-opacity duration-200 motion-reduce:transition-none dark:text-zinc-500"
          >
            <circle cx="8" cy="8" r="6" stroke="currentColor" strokeOpacity="0.3" strokeWidth="1.5" />
            <path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        ) : null}
      </div>
      {message ? (
        <p id={messageId} className={invalid ? "text-sm leading-5 text-red-600 dark:text-red-400" : "text-sm leading-5 text-zinc-500 dark:text-zinc-400"}>
          {message}
        </p>
      ) : null}
    </div>
  );
}

function InputOTPSlot({ index, length, invalid }: { index: number; length: number; invalid: boolean }) {
  const caretRef = useRef<HTMLSpanElement>(null);

  // A text caret blinks 500ms on, 500ms off. It restarts solid whenever the cell gains focus,
  // like a native caret, and does not blink at all when reduced motion is preferred.
  useEffect(() => {
    const caret = caretRef.current;
    if (!caret || typeof caret.animate !== "function") return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const animation = caret.animate(
      [
        { opacity: 1, offset: 0 },
        { opacity: 1, offset: 0.5 },
        { opacity: 0, offset: 0.5 },
        { opacity: 0, offset: 1 },
      ],
      { duration: 1000, iterations: Infinity },
    );
    return () => animation.cancel();
  }, []);

  return (
    <BaseOTPField.Input
      aria-label={index === 0 ? undefined : `Character ${index + 1} of ${length}`}
      onFocus={() => caretRef.current?.getAnimations().forEach((animation) => (animation.currentTime = 0))}
      className={cx(
        "peer size-full min-w-0 bg-transparent text-center font-mono text-lg text-zinc-950 caret-transparent outline-none tabular-nums dark:text-white",
        "disabled:cursor-not-allowed",
      )}
      render={(inputProps, state) => (
        <span
          data-filled={state.filled || undefined}
          className={cx(
            // Cells shrink toward 28px wide on narrow screens instead of overflowing.
            "relative flex h-10 w-9 min-w-7 rounded-lg border bg-white shadow-sm dark:bg-zinc-950",
            "transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
            invalid
              ? "border-red-400 has-focus:border-red-500 has-focus:ring-3 has-focus:ring-red-500/20 dark:border-red-500/60"
              : cx(
                  "border-zinc-300 dark:border-zinc-700",
                  "data-filled:border-zinc-400 dark:data-filled:border-zinc-600",
                  "has-focus:border-sky-500 has-focus:ring-3 has-focus:ring-sky-500/20",
                ),
          )}
        >
          <input {...inputProps} />
          <span
            ref={caretRef}
            aria-hidden="true"
            className={cx(
              "pointer-events-none absolute top-1/2 left-1/2 hidden h-5 w-px -translate-x-1/2 -translate-y-1/2 bg-zinc-950 dark:bg-white",
              !state.filled && "peer-focus:block",
            )}
          />
        </span>
      )}
    />
  );
}