Menu

Components

Input OTP

A code entered one character per box, for one-time passcodes and verification codes. Built on react-aria-components.

Introduction

Input OTP shows a short code as a row of boxes, one per character. It suits the codes people copy from an SMS or an authenticator app, where seeing each position makes a typo easy to spot.

  • Behind the boxes there is one real input, so typing, Backspace, pasting a whole code and SMS autofill all work as usual. On phones it opens the number keypad.
  • Only the characters you allow are kept: digits by default, or letters, or both.
  • Group the boxes, join them into one control, or hide the characters behind dots.
  • onComplete runs once the last character is entered, which is the moment to verify the code.

The cursor always stays after the last character: type to add, Backspace to remove. To fix a digit in the middle, delete back to it.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/input-otp-styles.tsShow code
import { tv } from "tailwind-variants";

// One box of an InputOTP. Its state comes from data attributes that the
// component sets (data-active, data-filled) and from the field around it
// (invalid, disabled) through the `group/otp` name.
export const inputOtpStyles = tv({
  slots: {
    slot: [
      "relative flex items-center justify-center border bg-bg font-medium tabular-nums transition-colors",
      "data-active:z-10 data-active:border-ring data-active:ring-2 data-active:ring-ring",
      "group-data-invalid/otp:border-danger group-data-invalid/otp:data-active:ring-danger",
      "group-data-disabled/otp:opacity-50",
    ],
    caret:
      "pointer-events-none absolute h-1/2 w-px animate-caret-blink bg-fg motion-reduce:animate-none",
  },
  variants: {
    size: {
      sm: { slot: "h-9 w-8 text-sm" },
      md: { slot: "h-10 w-9 text-base" },
      lg: { slot: "h-12 w-11 text-xl" },
    },
    // Attached slots share their borders and only the ends are rounded.
    isAttached: {
      true: {
        slot: "-ml-px first:ml-0 first:rounded-l-md last:rounded-r-md",
      },
      false: { slot: "rounded-md" },
    },
  },
  defaultVariants: { size: "md", isAttached: false },
});

2. Add the Input OTP file

src/components/ui/input-otp/input-otp.tsxShow code
"use client";

import { Fragment, type ReactNode, useState } from "react";
import {
  TextField as AriaTextField,
  type TextFieldProps as AriaTextFieldProps,
  FieldError,
  Input,
  Label,
  Text,
  type ValidationResult,
} from "react-aria-components";
import { MinusIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import { inputOtpStyles } from "@/types/input-otp-styles";

type Characters = "digits" | "letters" | "alphanumeric" | "any";

// What each set of characters accepts, and the keyboard a phone shows for it.
const characterSets: Record<
  Characters,
  { strip: RegExp; inputMode: "numeric" | "text" }
> = {
  digits: { strip: /[^0-9]/g, inputMode: "numeric" },
  letters: { strip: /[^a-zA-Z]/g, inputMode: "text" },
  alphanumeric: { strip: /[^a-zA-Z0-9]/g, inputMode: "text" },
  any: { strip: /\s/g, inputMode: "text" },
};

export interface InputOTPProps
  extends Omit<
    AriaTextFieldProps,
    | "children"
    | "className"
    | "type"
    | "inputMode"
    | "maxLength"
    | "minLength"
    | "pattern"
    | "autoComplete"
  > {
  label?: ReactNode;
  /** Help text under the field. */
  description?: ReactNode;
  /** Shown when the field is invalid. A function receives the validation result. */
  errorMessage?: string | ((validation: ValidationResult) => string);
  /** How many characters the code has, and so how many boxes are shown. */
  length?: number;
  /**
   * Split the boxes into groups with a dash between them, for example `[3, 3]`
   * for a 6-character code. The sizes must add up to `length`.
   */
  groups?: number[];
  /** Which characters are accepted. Anything else typed or pasted is dropped. */
  characters?: Characters;
  /** Show a dot instead of each character. */
  isMasked?: boolean;
  /** Join the boxes into one control. `false` keeps them apart with a gap. */
  isAttached?: boolean;
  /** Size of the boxes. */
  size?: "sm" | "md" | "lg";
  /** Runs once, when the last character is entered. */
  onComplete?: (value: string) => void;
  className?: string;
}

/**
 * A code made of one box per character, for one-time passcodes and
 * verification codes. There is a single real input behind the boxes, so
 * typing, deleting, pasting a whole code and the code suggested by a phone's
 * SMS autofill all work like in any text field. Built on react-aria's
 * TextField, so the label, description, error and form submission (`name`)
 * come from there.
 *
 * The cursor always stays after the last character: type to add, Backspace to
 * remove. Give it a `label`, or an `aria-label` when the label is elsewhere.
 *
 * @example
 * <InputOTP label="Verification code" length={6} onComplete={verify} />
 */
export function InputOTP({
  label,
  description,
  errorMessage,
  length = 6,
  groups,
  characters = "digits",
  isMasked = false,
  isAttached = false,
  size = "md",
  onComplete,
  className,
  value,
  defaultValue,
  onChange,
  ...props
}: InputOTPProps) {
  const styles = inputOtpStyles({ size, isAttached });
  const { strip, inputMode } = characterSets[characters];
  const clean = (text: string) => text.replace(strip, "").slice(0, length);

  // The text is always controlled underneath, so what is typed or pasted can be
  // cleaned before it reaches the input.
  const isControlled = value !== undefined;
  const [inner, setInner] = useState(clean(defaultValue ?? ""));
  const current = isControlled ? clean(value) : inner;
  const [isFocused, setFocused] = useState(false);

  // Boxes per group. Without `groups`, all of them are one group.
  const sizes =
    groups?.reduce((sum, n) => sum + n, 0) === length ? groups : [length];
  const activeIndex = Math.min(current.length, length - 1);

  let index = 0;

  return (
    <AriaTextField
      {...props}
      value={current}
      onChange={(raw) => {
        const next = clean(raw);
        if (!isControlled) setInner(next);
        onChange?.(next);
        if (next.length === length && next !== current) onComplete?.(next);
      }}
      className={cn(
        "group/otp flex w-fit max-w-full flex-col gap-1.5",
        className,
      )}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/otp:after:ml-0.5 group-data-required/otp:after:text-danger group-data-required/otp:after:content-['*']">
          {label}
        </Label>
      ) : null}
      <div className="relative w-fit max-w-full">
        <div
          aria-hidden="true"
          className={cn("flex items-center", isAttached ? "" : "gap-1.5")}
        >
          {sizes.map((count, groupIndex) => (
            <Fragment key={`group-${groupIndex}-${count}`}>
              {groupIndex > 0 ? (
                <MinusIcon className="mx-1 size-3.5 shrink-0 text-muted-fg" />
              ) : null}
              <div
                className={cn("flex items-center", isAttached ? "" : "gap-1.5")}
              >
                {Array.from({ length: count }, () => {
                  const slotIndex = index++;
                  const char = current[slotIndex];
                  const isActive = isFocused && slotIndex === activeIndex;
                  return (
                    <div
                      key={slotIndex}
                      data-active={isActive || undefined}
                      data-filled={char ? true : undefined}
                      className={styles.slot()}
                    >
                      {char ? (isMasked ? "•" : char) : null}
                      {isActive && !char ? (
                        <span className={styles.caret()} />
                      ) : null}
                    </div>
                  );
                })}
              </div>
            </Fragment>
          ))}
        </div>
        {/* The real input sits on top of the boxes, invisible, so a click
            anywhere focuses it and the browser handles every kind of input. */}
        <Input
          inputMode={inputMode}
          autoComplete="one-time-code"
          spellCheck={false}
          autoCapitalize="off"
          onFocus={(event) => {
            setFocused(true);
            const end = event.currentTarget.value.length;
            event.currentTarget.setSelectionRange(end, end);
          }}
          onBlur={() => setFocused(false)}
          // Keep the cursor after the last character, whatever was clicked.
          onSelect={(event) => {
            const input = event.currentTarget;
            const end = input.value.length;
            if (input.selectionStart !== end || input.selectionEnd !== end) {
              input.setSelectionRange(end, end);
            }
          }}
          className="absolute inset-0 size-full cursor-text bg-transparent text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed"
        />
      </div>
      {description ? (
        <Text slot="description" className="text-sm text-muted-fg">
          {description}
        </Text>
      ) : null}
      <FieldError className="text-sm text-danger">{errorMessage}</FieldError>
    </AriaTextField>
  );
}

It imports MinusIcon from @/components/icons for the separator. Add that icon, or swap it for your own.

3. Add the caret animation

In src/app/globals.css copy the caret-blink keyframes, and the --animate-caret-blink line in @theme inline. Without them the cursor in the active box stays solid instead of blinking.

4. Use it

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

Anatomy

A row of boxes over one invisible input.

<InputOTP
  label="Verification code"
  description="We sent it to your phone."
  length={6}
  groups={[3, 3]}
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the code.
BoxesdivOne per character. The next one to fill has a blinking cursor.
SeparatorsvgA dash between groups, when you set groups.
Inputinput, invisibleThe one real input, on top of the boxes. It receives typing, paste and the code suggested by SMS autofill.
Description / errortext under the fieldHelp text, replaced by the error message when the field is invalid.

Without a label, give the field an aria-label so a screen reader can name it. The boxes are hidden from screen readers: they read the input.

Examples

Click a code and type, or paste a whole code.

Usage

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Description

Help text under the field.

Enter the 6-digit code we sent to your phone.

Length

length sets how many characters the code has, and so how many boxes.

Groups

Split the boxes into groups with a dash between them. The sizes must add up to length.

Attached

Join the boxes into one control that shares its borders.

Characters

Which characters are kept. Anything else that is typed or pasted is dropped, and a phone shows the number keypad only for digits.

Masked

Show a dot instead of each character, for a PIN. The value is still the real one.

Uncontrolled

Let the field keep its own value. Start with defaultValue, and give it a name to read the value from a form.

Controlled

Keep the value in your own state with value and onChange, so you can read it, set it or clear it from outside.

value: “12”

On complete

onComplete runs once, when the last character is entered. Use it to verify the code and show an error if it is wrong.

Try 123456.

Enter all six digits.

Sizes

Disabled

Validation

Set isInvalid with an errorMessage. Every box gets a red border and the message shows under the field.

That code has expired.

Component API

Input OTP takes the props below, plus most of what the react-aria TextField accepts. The text-input props type, inputMode, maxLength, pattern and autoComplete are set for you.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
lengthnumber6
groupsnumber[]- (one group)
characters"digits" | "letters" | "alphanumeric" | "any""digits"
isMaskedbooleanfalse
isAttachedbooleanfalse
size"sm" | "md" | "lg""md"
valuestring-
defaultValuestring""
onChange(value: string) => void-
onComplete(value: string) => void-
namestring-
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)