When to use
- Verifying an email address or phone number with a short code.
- A second factor from an authenticator app.
- Any fixed-length code a person reads from somewhere else and types: a TV pairing code, a door PIN.
When not to use
- Codes of varying length, or long tokens: use an Input.
- Passwords: use an Input with
type="password"; codes are short-lived, passwords are not.
Installation
pnpm dlx shadcn add https://eased.dev/r/otp-field.jsonnpx shadcn add https://eased.dev/r/otp-field.jsonyarn dlx shadcn add https://eased.dev/r/otp-field.jsonbunx --bun shadcn add https://eased.dev/r/otp-field.jsonThe command adds OTP Field, everything it builds on and Eased’s tokens to your project.
Install the dependencies
pnpm add @base-ui/react motionnpm install @base-ui/react motionyarn add @base-ui/react motionbun add @base-ui/react motionAdd the Eased pieces it builds on
Copy each item’s files the same way, or install them with the CLI:
Copy the source into your project
components/eased/otp-field/otp-field.tsxTSX "use client";import { OTPField as BaseOTPField } from "@base-ui/react/otp-field";import { AnimatePresence, animate, motion } from "motion/react";import { Fragment, useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";import { useShakeOnInvalid } from "../_primitives/field/field";import { bouncy, ease, enter, exitFast, reducedFade, snappy, stagger, useSafeReducedMotion } from "../lib/motion";type RootProps = ComponentProps<typeof BaseOTPField.Root>;export type OtpFieldSize = "md" | "lg";export type OtpFieldProps = Omit<RootProps, "className" | "render" | "children" | "length" | "value" | "defaultValue" | "onValueChange"> & { /** Number of characters. Default 6. */ length?: number; /** * Cells per group, separated by a dash: `[3, 3]` for 123–456. Default: two halves for an even * length of 6 or more, else one group. Pass `[length]` for no separator. */ groups?: readonly number[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** * Mark the code wrong: danger borders and one shake when it turns on. Inside a `Field`, the * field's validity drives it too. */ invalid?: boolean; /** Mark the code accepted: success borders and a ripple across the cells when it turns on. */ success?: boolean; /** md 40×44 cells (default), lg 48×56. */ size?: OtpFieldSize; /** Accessible name for slots after the first, given its position. Default "Character 2 of 6". */ getSlotLabel?: (index: number, length: number) => string; className?: string;};const CELL: Record<OtpFieldSize, string> = { md: "h-11 w-10 rounded-control text-ui-lg", lg: "h-14 w-12 rounded-control text-display-xl",};function defaultGroups(length: number): number[] { if (length >= 6 && length % 2 === 0) return [length / 2, length / 2]; return [length];}/** * A one-time-code input on Base UI's OTPField: one input per cell, with `autocomplete="one-time-code"` * on the first, so an SMS or email autofill, a password manager or a paste fills every cell at * once. The caret blinks in the empty cell that has focus, each character pops in, a wrong code * shakes the row once, and an accepted one ripples green across it. */export function OtpField({ length = 6, groups: groupsProp, value: valueProp, defaultValue = "", onValueChange, invalid: invalidProp, success = false, size = "md", mask = false, disabled, getSlotLabel = (i, n) => `Character ${i + 1} of ${n}`, className = "", ...props}: OtpFieldProps) { const reduced = useSafeReducedMotion(); const [uncontrolled, setUncontrolled] = useState(defaultValue); const value = valueProp ?? uncontrolled; const [focusIndex, setFocusIndex] = useState<number | null>(null); const rowRef = useRef<HTMLDivElement>(null); const fieldInvalid = useDataInvalid(rowRef); const invalid = !disabled && (invalidProp ?? fieldInvalid); useShakeOnInvalid(rowRef, invalid, reduced); useRipple(rowRef, success && !invalid, reduced); const groups = groupsProp?.reduce((a, b) => a + b, 0) === length ? groupsProp : defaultGroups(length); const starts = groups.map((_, g) => groups.slice(0, g).reduce((a, b) => a + b, 0)); const tone = invalid ? "invalid" : success ? "success" : "idle"; return ( <BaseOTPField.Root {...props} ref={rowRef} length={length} value={value} mask={mask} disabled={disabled} onValueChange={(next) => { if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocusIndex(null); }} className={`flex w-fit max-w-full items-center gap-2 ${className}`} > {groups.map((count, g) => ( <Fragment key={g}> {g > 0 && ( <BaseOTPField.Separator className="flex w-2 shrink-0 items-center justify-center" render={<span />}> <span className={`h-0.5 w-2 rounded-pill ${disabled ? "bg-text-disabled" : "bg-line-strong"}`} /> </BaseOTPField.Separator> )} <div className="flex items-center gap-1.5"> {Array.from({ length: count }, (_, k) => { const i = starts[g] + k; const char = value[i] ?? ""; const focused = focusIndex === i; return ( <div key={i} data-otp-cell="" data-tone={tone} data-focused={focused || undefined} data-filled={char ? "" : undefined} className={`relative flex shrink-0 items-center justify-center border font-medium tabular-nums ${disabled ? "bg-surface-sunken" : "bg-surface"} transition-[border-color,box-shadow,color,background-color] duration-(--eased-duration-standard) ease-standard reduced:transition-none ${CELL[size]} ${ disabled ? "cursor-not-allowed border-line text-text-disabled" : tone === "invalid" ? `border-danger text-text ${focused ? "shadow-[0_0_0_3px_var(--eased-ring-danger)]" : ""}` : tone === "success" ? "border-success text-success-text" : focused ? "border-(--eased-neutral-9) text-text shadow-[0_0_0_3px_var(--eased-ring-soft)]" : "border-line-strong text-text hover-fine:border-(--eased-neutral-9)" }`} > <BaseOTPField.Input // Base UI names the first slot from the field's label; the rest by position. aria-label={i > 0 ? getSlotLabel(i, length) : undefined} {...(invalidProp !== undefined ? { "aria-invalid": invalidProp || undefined } : null)} onFocus={() => setFocusIndex(i)} className="absolute inset-0 size-full cursor-text rounded-[inherit] bg-transparent text-center text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed" /> <span aria-hidden className="pointer-events-none relative flex size-full items-center justify-center"> <AnimatePresence initial={false} mode="popLayout"> {char ? ( <motion.span key={`${i}:${char}`} initial={reduced ? { opacity: 0 } : { opacity: 0, scale: 0.5, y: 3, filter: "blur(2px)" }} animate={{ opacity: 1, scale: 1, y: 0, filter: "blur(0px)" }} exit={reduced ? { opacity: 0, transition: reducedFade } : { opacity: 0, scale: 0.7, filter: "blur(2px)", transition: exitFast }} transition={reduced ? reducedFade : { scale: bouncy, y: snappy, opacity: enter, filter: enter }} className="inline-block" > {mask ? "•" : char} </motion.span> ) : focused && !disabled ? ( <Caret key="caret" reduced={reduced} size={size} /> ) : null} </AnimatePresence> </span> </div> ); })} </div> </Fragment> ))} </BaseOTPField.Root> );}/** A 1.5px caret that holds, fades out, holds and fades back in, like a native text field. Static under reduced motion. */function Caret({ reduced, size, ref }: { reduced: boolean; size: OtpFieldSize; ref?: React.Ref<HTMLSpanElement> }) { return ( <motion.span ref={ref} initial={{ opacity: 0 }} animate={reduced ? { opacity: 1 } : { opacity: [1, 1, 0, 0, 1] }} exit={{ opacity: 0, transition: { duration: 0 } }} transition={reduced ? reducedFade : { duration: 1.1, times: [0, 0.45, 0.55, 0.9, 1], ease: "linear", repeat: Infinity }} className={`block w-[1.5px] rounded-pill bg-text ${size === "lg" ? "h-7" : "h-5"}`} /> );}/** Whether Base UI marked the field invalid (a `Field`'s validation or `<Form errors>`). */function useDataInvalid(ref: React.RefObject<HTMLElement | null>) { const [invalid, setInvalid] = useState(false); useLayoutEffect(() => { const el = ref.current; if (!el) return; const read = () => setInvalid(el.hasAttribute("data-invalid")); read(); const mo = new MutationObserver(read); mo.observe(el, { attributes: true, attributeFilter: ["data-invalid"] }); return () => mo.disconnect(); }, [ref]); return invalid;}/** A left-to-right lift across the cells when `on` turns on: 2px up and back, 35ms apart. Reduced motion: none. */function useRipple(ref: React.RefObject<HTMLElement | null>, on: boolean, reduced: boolean) { const was = useRef(on); useEffect(() => { const turnedOn = on && !was.current; was.current = on; if (!turnedOn || reduced || !ref.current) return; const cells = ref.current.querySelectorAll<HTMLElement>("[data-otp-cell]"); const runs = [...cells].map((cell, i) => animate(cell, { y: [0, -3, 0], scale: [1, 1.04, 1] }, { duration: 0.32, delay: i * stagger.item, ease: ease.standard }), ); return () => runs.forEach((r) => r.stop()); }, [on, reduced, ref]);}Keep the folder layout
The files import each other by relative path (
../lib/motion), so keep each one at the path shown, undercomponents/eased/.
Usage
import { useState } from "react";import { Field } from "@/components/eased/field/field";import { OtpField } from "@/components/eased/otp-field/otp-field";export function Example() { const [code, setCode] = useState(""); return ( <Field label="Verification code" description="We sent it to maya@northwind.com."> <OtpField value={code} onValueChange={setCode} onValueComplete={(c) => verify(c)} /> </Field> );}Examples
Wrong and right codes
Pass invalid (or a Field error) when the server rejects the code: the row shakes once. Pass success when it's accepted.
<Field label="Code" error={wrong ? "That code doesn’t match." : undefined}> <OtpField value={code} onValueChange={setCode} success={verified} readOnly={verified} /></Field>Grouping and letters
<OtpField length={8} groups={[4, 4]} validationType="alphanumeric" />API reference
OtpField
| Prop | Type | Default | Description |
|---|---|---|---|
length | number | 6 | Number of cells. |
groups | number[] | halves for even lengths ≥ 6 | Cells per group, separated by a dash. [length] for none. Ignored unless it sums to length. |
value | string | Controlled code. | |
defaultValue | string | "" | Uncontrolled starting code. |
onValueChange | (value: string) => void | Every change: typing, deleting, paste and autofill. | |
onValueComplete | (value: string) => void | When every cell is filled. | |
invalid | boolean | Danger borders and one shake when it turns on. Inside a Field, the field's validity drives it too. | |
success | boolean | false | Success borders and a ripple when it turns on. |
size | "md" | "lg" | "md" | 40×44 or 48×56 cells. |
mask | boolean | false | Show dots instead of characters. |
getSlotLabel | (index, length) => string | "Character 2 of 6" | Accessible names for cells after the first. |
className | string | "" | Appended to the root's classes. |
Base UI's other OTPField.Root props pass through: validationType ("numeric" by default, "alpha", "alphanumeric", "none"), normalizeValue, onValueInvalid, autoSubmit, name, form, required, disabled, readOnly, autoComplete, inputMode.
Keyboard
| Key | Action |
|---|---|
| Characters | Fill the focused cell and move to the next. |
Backspace | Clears the cell, then moves back. |
← / → | Moves between filled cells. |
Home / End | First cell, or the first empty one. |
⌘V / Ctrl V | Pastes a whole code into every cell; spaces and dashes are dropped. |
Accessibility
- The first cell is named by the Field label; the others are "Character 2 of 6" and so on.
- Only one cell is in the tab order, so Tab leaves the field in one step.
- Errors are announced by the Field's message line; the shake is never the only signal (the borders turn danger).
- Mobile keyboards open numeric and offer the code from the latest SMS.
Motion
Each character pops in from half size and a 2px blur, scale on the bouncy spring and position on snappy, and leaves in 100ms at 0.7 scale. The caret in the focused empty cell holds, fades and holds again on a 1.1s cycle, like a native text field. A wrong code shakes the row once, 6px, on the shared field shake; an accepted code ripples left to right, each cell lifting 3px and 4% then settling, 35ms apart. Reduced motion: characters fade in 100ms, the caret stays still, and there is no shake or ripple (the colours carry the state).
Notes for AI
Use OtpField for fixed-length codes only, inside a Field for its label and error. Verify in onValueComplete, set readOnly while checking, then set invalid or success from the result; clear invalid when the person edits.
Don't render your own inputs per cell or a hidden input next to it, and don't intercept paste: Base UI already spreads pasted and autofilled codes and filters characters by validationType.
Related components
- Animated Text Input: for codes of any length.
- Form Field with Validation: the label and message line around it.
- Number Input with Steppers