Skip to content
Components

OTP Input

OTP Input for a useful, keyboard-friendly product interface.

Open ↗

Make it yours.

Install the editable source and its dependencies into your React + Tailwind project.

Scroll horizontally for long lines
pnpm dlx shadcn@4.0.8 add http://localhost:3000/r/otp-input.json

Use it

Scroll horizontally for long lines
"use client";
import {OtpInput} from '@/components/jez-ui/ui/otp-input';

export default function Example(){

return <><div className="w-full max-w-sm"><div className="mb-7"><h3 className="text-2xl tracking-tight">A quick check.</h3><p className="mt-2 text-sm leading-relaxed text-muted-foreground">Enter the six-digit code to continue this demo.</p></div><OtpInput/></div></>;
}

Props & types

Scroll horizontally for long lines
{
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  length?: number;
  className?: string;
}

Source

View 3 source files

registry/ui/otp-input.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { cn } from "./utils";
import { useControllable } from "./use-controllable";
export function OtpInput({
  value,
  defaultValue = "",
  onValueChange,
  length = 6,
  className,
}: {
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  length?: number;
  className?: string;
}) {
  const [code, setCode] = useControllable(value, defaultValue, onValueChange);
  return (
    <label className={cn("grid gap-2 text-sm", className)}>
      Verification code
      <input
        aria-label={`${length}-digit verification code`}
        inputMode="numeric"
        autoComplete="one-time-code"
        pattern={`[0-9]{${length}}`}
        maxLength={length}
        value={code}
        onChange={(e) =>
          setCode(e.target.value.replace(/\D/g, "").slice(0, length))
        }
        className="w-full max-w-72 rounded-xl border border-border bg-background px-4 py-3 text-center font-mono text-2xl tracking-[.4em]"
      />
    </label>
  );
}

registry/ui/utils.ts

Scroll horizontally for long lines
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...values: ClassValue[]) {
  return twMerge(clsx(values));
}

registry/ui/use-controllable.ts

Scroll horizontally for long lines
"use client";
import { useState } from "react";
export function useControllable<T>(
  value: T | undefined,
  initial: T,
  onChange?: (value: T) => void,
) {
  const [local, setLocal] = useState(initial);
  return [
    value === undefined ? local : value,
    (next: T) => {
      if (value === undefined) setLocal(next);
      onChange?.(next);
    },
  ] as const;
}

Dependencies

clsx@2.1.1 · tailwind-merge@3.5.0

Accessibility & behaviour

Provide meaningful labels and preserve keyboard focus styles. Check contrast when customising theme colours.

Read the accessibility and performance guide →