Skip to the content

Controls and surfaces

otp-field

A one-time code typed into one box per character: typing moves on, Backspace moves back, and a pasted code fills every box.

Primitives

When to use it

A short code sent by message or read from an authenticator. It posts as one value under name, and the browser can offer the code it has just received. Label it with aria-label, or put it in a field with FieldControl group. For a password use password-field; for any other short text use input.

See it working

The demonstration the browser checks drive, with the keyboard as well as the pointer. More of it is on the Primitives page.

Alert dialog

The project is kept.

Collapsible

The options are closed.

Hover card

The first published program was written by Ada Lovelace.

Menubar

Command: none yet. Ruler: hidden. Zoom: 100.

Navigation menu

Toolbar

Styles: none. Saved 0 times.

One-time code

Typed: nothing yet. Sent: nothing yet.

Password

At least twelve characters.

Words for screen readers

Add it

npx shadcn@latest add @rivier-ui/otp-field

The registry is named once in components.json: see Installation.

Example

Import it from @/components/ui/otp-field.

<OtpField name="code" aria-label="Verification code" onAutoSubmit={verify} autoSubmit />
<OtpField length={4} validationType="alphanumeric" value={code} onValueChange={setCode} />

What it needs

A client component: it uses state, effects or browser behaviour. Packages: radix-ui.

It imports

Source

The whole file. Once copied it is yours: the registry item holds the same text.

src/components/ui/otp-field.tsx
"use client";
/**
 * @name otp-field
 * @category ui
 * @description A one-time code typed into one box per character: typing moves on, Backspace moves back, and a pasted code fills every box.
 * @when A short code sent by message or read from an authenticator. It posts as one value under `name`, and the browser can offer the code it has just received. Label it with `aria-label`, or put it in a field with FieldControl group. For a password use password-field; for any other short text use input.
 * @example
 * <OtpField name="code" aria-label="Verification code" onAutoSubmit={verify} autoSubmit />
 * <OtpField length={4} validationType="alphanumeric" value={code} onValueChange={setCode} />
 */
import { unstable_OneTimePasswordField as OtpPrimitive } from "radix-ui";
import { createContext, use, type ComponentProps } from "react";
import { cn } from "@/lib/cn";

type Naming = (position: number, length: number) => string;

const defaultNaming: Naming = (position, length) => `Character ${position} of ${length}`;

const OtpFieldContext = createContext<{ length: number; inputLabel: Naming }>({ length: 6, inputLabel: defaultNaming });

export type OtpFieldProps = ComponentProps<typeof OtpPrimitive.Root> & {
  /** How many characters the code has. */
  length?: number;
  /** The accessible name of each box, from its position (from 1) and the length. Translate it with the rest of the interface. */
  inputLabel?: Naming;
};

/**
 * Holds the value: `value`, `defaultValue`, `onValueChange`; `onAutoSubmit` with `autoSubmit` when the last
 * character is typed. `validationType` is "numeric" (the default), "alpha", "alphanumeric" or "none". With no
 * children it draws `length` boxes; pass OtpFieldInput children to arrange them yourself (a gap in the middle).
 */
export function OtpField({ className, length = 6, inputLabel = defaultNaming, children, ...props }: OtpFieldProps) {
  return (
    <OtpFieldContext value={{ length, inputLabel }}>
      <OtpPrimitive.Root data-slot="otp-field" className={cn("flex w-fit max-w-full items-center gap-2", className)} {...props}>
        {children ?? Array.from({ length }, (_, index) => <OtpFieldInput key={index} index={index} />)}
        <OtpPrimitive.HiddenInput />
      </OtpPrimitive.Root>
    </OtpFieldContext>
  );
}

export type OtpFieldInputProps = ComponentProps<typeof OtpPrimitive.Input> & {
  /** The box's place in the code, from 0: it gives the box its name. */
  index: number;
};

/** One box. */
export function OtpFieldInput({ className, index, ...props }: OtpFieldInputProps) {
  const { length, inputLabel } = use(OtpFieldContext);
  return (
    <OtpPrimitive.Input
      data-slot="otp-field-input"
      aria-label={inputLabel(index + 1, length)}
      className={cn(
        "size-(--control-h) min-w-0 shrink rounded-control border border-input bg-background text-center text-base text-foreground transition-[border-color,opacity] duration-instant ease-out disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive motion-reduce:transition-none",
        className,
      )}
      {...props}
    />
  );
}