Get Started
Components
- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
AI Elements
Libraries
Utilities
1
2
3
4
5
6
"use client";
import { MinusIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const digits = "^\\d+$";
const chars = "^[a-zA-Z]+$";
const alphanumeric = "^[a-zA-Z0-9]+$";
interface SlotProps {
char: string | null;
hasFakeCaret: boolean;
isActive: boolean;
placeholderChar: string | null;
}
interface RenderProps {
isFocused: boolean;
isHovering: boolean;
slots: SlotProps[];
}
const OTPInputContext = React.createContext<RenderProps>({
isFocused: false,
isHovering: false,
slots: [],
});
type OTPInputBaseProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "onChange" | "maxLength" | "pattern" | "placeholder"
> & {
containerClassName?: string;
maxLength: number;
onChange?: (value: string) => void;
pattern?: string;
placeholder?: string;
value?: string;
};
type OTPInputProps = OTPInputBaseProps & {
children?: React.ReactNode;
};
const InputOTP = React.forwardRef<HTMLInputElement, OTPInputProps>(
function InputOTP(
{
children,
className,
containerClassName,
defaultValue,
disabled,
id,
inputMode = "numeric",
maxLength,
onChange,
onFocus,
onBlur,
pattern,
placeholder,
value: valueProp,
...props
},
forwardedRef
) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<string>(
typeof defaultValue === "string" ? defaultValue : ""
);
const value = isControlled ? valueProp : uncontrolled;
const [isFocused, setIsFocused] = React.useState(false);
const [isHovering, setIsHovering] = React.useState(false);
const [selectionStart, setSelectionStart] = React.useState(0);
const [selectionEnd, setSelectionEnd] = React.useState(0);
const inputRef = React.useRef<HTMLInputElement>(null);
const setRef = React.useCallback(
(node: HTMLInputElement | null) => {
inputRef.current = node;
if (typeof forwardedRef === "function") {
forwardedRef(node);
} else if (forwardedRef) {
(
forwardedRef as React.MutableRefObject<HTMLInputElement | null>
).current = node;
}
},
[forwardedRef]
);
const filterValue = React.useCallback(
(raw: string): string => {
let next = raw.slice(0, maxLength);
if (pattern) {
const re = new RegExp(pattern);
if (!re.test(next)) {
next = next
.split("")
.filter((c) => new RegExp(pattern.replace(/[+*]$/, "")).test(c))
.join("");
}
}
return next;
},
[maxLength, pattern]
);
const commit = React.useCallback(
(next: string) => {
const filtered = filterValue(next);
if (!isControlled) {
setUncontrolled(filtered);
}
onChange?.(filtered);
},
[filterValue, isControlled, onChange]
);
const updateSelection = React.useCallback(() => {
const el = inputRef.current;
if (!el) {
return;
}
setSelectionStart(el.selectionStart ?? 0);
setSelectionEnd(el.selectionEnd ?? 0);
}, []);
const slots = React.useMemo<SlotProps[]>(
() =>
Array.from({ length: maxLength }).map((_, i) => {
const char = value[i] ?? null;
const active =
isFocused &&
((selectionStart === selectionEnd && i === selectionStart) ||
(i >= selectionStart && i < selectionEnd));
return {
char,
hasFakeCaret: active && char === null,
isActive: active,
placeholderChar: null,
};
}),
[value, maxLength, isFocused, selectionStart, selectionEnd]
);
const contextValue = React.useMemo<RenderProps>(
() => ({ isFocused, isHovering, slots }),
[isFocused, isHovering, slots]
);
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
commit(event.currentTarget.value);
updateSelection();
};
const handleSelect = () => updateSelection();
const handleClick = () => {
inputRef.current?.focus();
updateSelection();
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
props.onKeyDown?.(event);
if (event.defaultPrevented) {
return;
}
requestAnimationFrame(updateSelection);
};
return (
<OTPInputContext.Provider value={contextValue}>
<div
className={cn("cn-input-otp flex items-center", containerClassName)}
data-slot="input-otp"
onClick={handleClick}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
<input
aria-label={props["aria-label"] ?? "One-time password"}
autoComplete="one-time-code"
className={cn(
"pointer-events-none absolute inset-0 -z-10 opacity-0",
className
)}
data-input-otp=""
defaultValue={
isControlled ? undefined : (defaultValue as string | undefined)
}
disabled={disabled}
id={id}
inputMode={inputMode}
maxLength={maxLength}
onBlur={(e) => {
setIsFocused(false);
onBlur?.(e);
}}
onChange={handleInput}
onFocus={(e) => {
setIsFocused(true);
updateSelection();
onFocus?.(e);
}}
onKeyDown={handleKeyDown}
onSelect={handleSelect}
pattern={pattern}
placeholder={placeholder}
ref={setRef}
value={isControlled ? value : undefined}
{...props}
/>
{children}
</div>
</OTPInputContext.Provider>
);
}
);
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"has-aria-invalid:border-destructive has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40 flex items-center rounded-lg has-aria-invalid:ring-3",
className
)}
data-slot="input-otp-group"
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & { index: number }) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index] ?? {};
return (
<div
className={cn(
"border-input aria-invalid:border-destructive data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40 relative flex size-8 items-center justify-center border-y border-r text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg data-[active=true]:z-10 data-[active=true]:ring-3",
className
)}
data-active={isActive}
data-slot="input-otp-slot"
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div
className="flex items-center [&_svg:not([class*='size-'])]:size-4"
data-slot="input-otp-separator"
role="separator"
{...props}
>
<MinusIcon />
</div>
);
}
export {
alphanumeric,
chars,
digits,
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
};Input OTP renders a one-time password field with real input handling for paste, backspace, and arrow keys. Each slot is a separate visual box, but the underlying input is a single element for form submission.
Installation
$ bunx --bun frakment add input-otp$ npx frakment add input-otp$ pnpm dlx frakment add input-otp$ yarn dlx frakment add input-otp
Install the following dependency:
$ bun add lucide-react$ npm install lucide-react$ pnpm add lucide-react$ yarn add lucide-react
Copy and paste the following code into your project.
"use client";
import { MinusIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const digits = "^\\d+$";
const chars = "^[a-zA-Z]+$";
const alphanumeric = "^[a-zA-Z0-9]+$";
interface SlotProps {
char: string | null;
hasFakeCaret: boolean;
isActive: boolean;
placeholderChar: string | null;
}
interface RenderProps {
isFocused: boolean;
isHovering: boolean;
slots: SlotProps[];
}
const OTPInputContext = React.createContext<RenderProps>({
isFocused: false,
isHovering: false,
slots: [],
});
type OTPInputBaseProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "onChange" | "maxLength" | "pattern" | "placeholder"
> & {
containerClassName?: string;
maxLength: number;
onChange?: (value: string) => void;
pattern?: string;
placeholder?: string;
value?: string;
};
type OTPInputProps = OTPInputBaseProps & {
children?: React.ReactNode;
};
const InputOTP = React.forwardRef<HTMLInputElement, OTPInputProps>(
function InputOTP(
{
children,
className,
containerClassName,
defaultValue,
disabled,
id,
inputMode = "numeric",
maxLength,
onChange,
onFocus,
onBlur,
pattern,
placeholder,
value: valueProp,
...props
},
forwardedRef
) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<string>(
typeof defaultValue === "string" ? defaultValue : ""
);
const value = isControlled ? valueProp : uncontrolled;
const [isFocused, setIsFocused] = React.useState(false);
const [isHovering, setIsHovering] = React.useState(false);
const [selectionStart, setSelectionStart] = React.useState(0);
const [selectionEnd, setSelectionEnd] = React.useState(0);
const inputRef = React.useRef<HTMLInputElement>(null);
const setRef = React.useCallback(
(node: HTMLInputElement | null) => {
inputRef.current = node;
if (typeof forwardedRef === "function") {
forwardedRef(node);
} else if (forwardedRef) {
(
forwardedRef as React.MutableRefObject<HTMLInputElement | null>
).current = node;
}
},
[forwardedRef]
);
const filterValue = React.useCallback(
(raw: string): string => {
let next = raw.slice(0, maxLength);
if (pattern) {
const re = new RegExp(pattern);
if (!re.test(next)) {
next = next
.split("")
.filter((c) => new RegExp(pattern.replace(/[+*]$/, "")).test(c))
.join("");
}
}
return next;
},
[maxLength, pattern]
);
const commit = React.useCallback(
(next: string) => {
const filtered = filterValue(next);
if (!isControlled) {
setUncontrolled(filtered);
}
onChange?.(filtered);
},
[filterValue, isControlled, onChange]
);
const updateSelection = React.useCallback(() => {
const el = inputRef.current;
if (!el) {
return;
}
setSelectionStart(el.selectionStart ?? 0);
setSelectionEnd(el.selectionEnd ?? 0);
}, []);
const slots = React.useMemo<SlotProps[]>(
() =>
Array.from({ length: maxLength }).map((_, i) => {
const char = value[i] ?? null;
const active =
isFocused &&
((selectionStart === selectionEnd && i === selectionStart) ||
(i >= selectionStart && i < selectionEnd));
return {
char,
hasFakeCaret: active && char === null,
isActive: active,
placeholderChar: null,
};
}),
[value, maxLength, isFocused, selectionStart, selectionEnd]
);
const contextValue = React.useMemo<RenderProps>(
() => ({ isFocused, isHovering, slots }),
[isFocused, isHovering, slots]
);
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
commit(event.currentTarget.value);
updateSelection();
};
const handleSelect = () => updateSelection();
const handleClick = () => {
inputRef.current?.focus();
updateSelection();
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
props.onKeyDown?.(event);
if (event.defaultPrevented) {
return;
}
requestAnimationFrame(updateSelection);
};
return (
<OTPInputContext.Provider value={contextValue}>
<div
className={cn("cn-input-otp flex items-center", containerClassName)}
data-slot="input-otp"
onClick={handleClick}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
<input
aria-label={props["aria-label"] ?? "One-time password"}
autoComplete="one-time-code"
className={cn(
"pointer-events-none absolute inset-0 -z-10 opacity-0",
className
)}
data-input-otp=""
defaultValue={
isControlled ? undefined : (defaultValue as string | undefined)
}
disabled={disabled}
id={id}
inputMode={inputMode}
maxLength={maxLength}
onBlur={(e) => {
setIsFocused(false);
onBlur?.(e);
}}
onChange={handleInput}
onFocus={(e) => {
setIsFocused(true);
updateSelection();
onFocus?.(e);
}}
onKeyDown={handleKeyDown}
onSelect={handleSelect}
pattern={pattern}
placeholder={placeholder}
ref={setRef}
value={isControlled ? value : undefined}
{...props}
/>
{children}
</div>
</OTPInputContext.Provider>
);
}
);
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"has-aria-invalid:border-destructive has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40 flex items-center rounded-lg has-aria-invalid:ring-3",
className
)}
data-slot="input-otp-group"
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & { index: number }) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index] ?? {};
return (
<div
className={cn(
"border-input aria-invalid:border-destructive data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40 relative flex size-8 items-center justify-center border-y border-r text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg data-[active=true]:z-10 data-[active=true]:ring-3",
className
)}
data-active={isActive}
data-slot="input-otp-slot"
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div
className="flex items-center [&_svg:not([class*='size-'])]:size-4"
data-slot="input-otp-separator"
role="separator"
{...props}
>
<MinusIcon />
</div>
);
}
export {
alphanumeric,
chars,
digits,
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
};Update the import paths to match your project setup.
Usage
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";<InputOTP maxLength={6}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>Examples
Pattern
digits restricts input to numbers.
"use client";
import { Field, FieldLabel } from "@/components/ui/field";
import {
digits,
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPPattern() {
return (
<Field className="w-fit">
<FieldLabel htmlFor="digits-only">Digits Only</FieldLabel>
<InputOTP id="digits-only" maxLength={6} pattern={digits}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</Field>
);
}With separator
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPWithSeparator() {
return (
<InputOTP maxLength={6}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
);
}Controlled
Drive the value from your own state.
Enter your one-time password.
"use client";
import * as React from "react";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPControlled() {
const [value, setValue] = React.useState("");
return (
<div className="space-y-2">
<InputOTP maxLength={6} onChange={setValue} value={value}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
<div className="text-center text-sm">
{value === "" ? (
<>Enter your one-time password.</>
) : (
<>You entered: {value}</>
)}
</div>
</div>
);
}Invalid
Set aria-invalid on slots to mark them invalid.
0
0
0
0
0
0
"use client";
import * as React from "react";
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPInvalid() {
const [value, setValue] = React.useState("000000");
return (
<InputOTP maxLength={6} onChange={setValue} value={value}>
<InputOTPGroup>
<InputOTPSlot aria-invalid index={0} />
<InputOTPSlot aria-invalid index={1} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot aria-invalid index={2} />
<InputOTPSlot aria-invalid index={3} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot aria-invalid index={4} />
<InputOTPSlot aria-invalid index={5} />
</InputOTPGroup>
</InputOTP>
);
}Alphanumeric
alphanumeric allows letters and numbers.
"use client";
import {
alphanumeric,
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPAlphanumeric() {
return (
<InputOTP maxLength={6} pattern={alphanumeric}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
);
}Disabled
1
2
3
4
5
6
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPDisabled() {
return (
<InputOTP disabled id="disabled" maxLength={6} value="123456">
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
);
}Four digits
"use client";
import {
digits,
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/components/ui/input-otp";
export function InputOTPFourDigits() {
return (
<InputOTP maxLength={4} pattern={digits}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
</InputOTPGroup>
</InputOTP>
);
}In Context
Verification code
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
import { Label } from "@/components/ui/label";
export function InputOTPVerification() {
return (
<div className="mx-auto flex w-full max-w-sm flex-col items-center gap-2">
<Label>Verification code</Label>
<InputOTP maxLength={6}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</div>
);
}API Reference
InputOTP
| Prop | Type | Default | Description |
|---|---|---|---|
maxLength | number | — | Number of character slots. |
value | string | — | Controlled value. |
onChange | function | — | Called with the new value. |
pattern | string | — | Regex string that limits allowed characters. |
disabled | boolean | false | Prevent input. |
containerClassName | string | — | Applied to the input container. |
InputOTPSlot
| Prop | Type | Default | Description |
|---|---|---|---|
index | number | — | Position of this slot within the input. |
Controlled
const [value, setValue] = React.useState("")
<InputOTP value={value} onChange={setValue} maxLength={6}>{/* ... */}</InputOTP>States
| State | How |
|---|---|
| Empty | default |
| Partial | some slots filled |
| Complete | all slots filled |
| Invalid | aria-invalid="true" |
Keyboard
| Key | Action |
|---|---|
← / → | Move between slots |
Backspace | Delete and move back |
Ctrl + V / Cmd + V | Paste the full code |
Data Attributes
| Attribute | Values |
|---|---|
data-slot | input-otp, input-otp-group, input-otp-slot, input-otp-separator |
data-active | true (caret in this slot) |
Accessibility
- The wrapper renders a real
<input>withinputmode="numeric"for mobile keyboards. - Slots expose
data-activeanddata-invalidfor styling, but the input itself carriesaria-invalid. - Paste, backspace, and arrow navigation are handled automatically.
- Pair with
FieldLabel htmlForandidfor labelled forms.
Best Practices
- Use
maxLengthmatching the code length. Do not let the input grow arbitrarily. - Group visually, not semantically. 3 + 3 reads better than 6 in one row.
- Auto-focus the first slot on mount. Reduces taps on mobile.
- Paste support is required. Users copy codes from messages; paste should fill every slot.