A field for a short code the user received elsewhere: an SMS or email verification code, an authenticator's six digits, a PIN. It looks like a row of boxes and is one text input with autocomplete="one-time-code", so typing, paste, the keyboard's SMS suggestion and a password manager all fill it as they fill any input. The library adds the boxes, a filter that keeps the text a code, and the asynchronous half: the moment the code is complete is a request, completeAction, run in a transition with data-pending.
Enter the 6-digit code we sent to your phone (try 123456).
"use client";
import { startTransition, useRef, useState } from "react";
import { OTPField } from "@funstack/ui/otp-field";
import { sleep } from "./fake-api.js";
const SLOTS = [0, 1, 2, 3, 4, 5];
// A pretend server check. A wrong code is not an error: it resolves with a message.
async function checkCode(code: string): Promise<{ ok: true } | { ok: false; message: string }> {
await sleep(900);
return code === "123456"
? { ok: true }
: { ok: false, message: "That code is not right. Check the message and try again." };
}
// Try a wrong code: the field pends while the server checks, then clears with a message. Type
// 123456: verified. Paste "123 456" or "123-456" too; the filter keeps the digits. The check runs
// once per completed code, and again when the same code is entered again.
export function OTPFieldVerify() {
const [code, setCode] = useState("");
const [message, setMessage] = useState<string | null>(null);
const [verified, setVerified] = useState(false);
// The latest text, for the check to compare against after its await.
const current = useRef("");
if (verified) {
return (
<div className="demo-otp-done">
<p className="demo-readout">Verified. Welcome back.</p>
<button
type="button"
className="demo-button"
onClick={() => {
setVerified(false);
current.current = "";
setCode("");
}}
>
Start over
</button>
</div>
);
}
return (
<div className="demo-otp-form">
<label htmlFor="verify-code" className="demo-label">
Verification code
</label>
<p id="verify-hint" className="demo-description">
Enter the 6-digit code we sent to your phone (try 123456).
</p>
<OTPField.Root
length={6}
value={code}
onValueChange={(next) => {
current.current = next;
setCode(next);
setMessage(null);
}}
completeAction={async (entered) => {
const result = await checkCode(entered);
// The user may have edited the code meanwhile: act on the current one only.
if (entered !== current.current) return;
if (result.ok) {
startTransition(() => setVerified(true));
return;
}
setMessage(result.message);
current.current = "";
setCode("");
}}
className="demo-otp"
>
<OTPField.Input
id="verify-code"
aria-describedby="verify-hint verify-message"
className="demo-otp-input"
/>
{SLOTS.map((i) => (
<OTPField.Slot key={i} index={i} className="demo-otp-slot" />
))}
</OTPField.Root>
<p id="verify-message" role="status" className="demo-field-error">
{message}
</p>
</div>
);
}/* OTPField: the Root is the box, the Input covers it with transparent text (the library's inline
style), and the Slots draw the characters, the caret and the focus. */
.demo-otp-form {
display: grid;
gap: 0.35rem;
justify-items: start;
}
.demo-otp {
display: inline-flex;
gap: 0.4rem;
border-radius: 8px;
}
.demo-otp-input {
border-radius: 8px;
/* 16px or more: iOS does not zoom on focus. */
font-size: 1rem;
outline: none;
}
.demo-otp-input::selection {
background: transparent;
}
/* The focus ring is drawn on the row while the input has keyboard or pointer focus. */
.demo-otp:has(.demo-otp-input:focus-visible) .demo-otp-slot[data-active] {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
.demo-otp-slot {
display: grid;
place-items: center;
inline-size: 2.5rem;
block-size: 3rem;
border: 1px solid var(--color-border);
border-radius: 8px;
background: var(--color-bg);
color: var(--color-text);
font:
600 1.25rem / 1 ui-monospace,
monospace;
font-variant-numeric: tabular-nums;
}
.demo-otp-slot[data-active] {
border-color: var(--color-primary);
}
/* The drawn caret in an empty active slot. */
.demo-otp-slot[data-active]:not([data-filled])::after {
content: "";
inline-size: 1px;
block-size: 1.25em;
background: currentColor;
animation: demo-otp-caret 1s steps(1) infinite;
}
@keyframes demo-otp-caret {
50% {
opacity: 0;
}
}
.demo-otp[data-pending] .demo-otp-slot {
opacity: 0.6;
}
.demo-otp[data-pending] .demo-otp-input {
cursor: progress;
}
.demo-otp[data-invalid] .demo-otp-slot {
border-color: #dc2626;
}
.demo-otp-done {
display: grid;
gap: 0.5rem;
justify-items: start;
}
@media (prefers-reduced-motion: reduce) {
.demo-otp-slot::after {
animation: none;
}
}
/* Without JavaScript the Slots never fill: show the plain input instead. */
@media (scripting: none) {
.demo-otp-slot {
display: none;
}
.demo-otp-input {
position: static !important;
color: inherit !important;
caret-color: auto !important;
border: 1px solid var(--color-border) !important;
padding: 0.5rem !important;
}
}import { OTPField } from "@funstack/ui/otp-field";
import { Separator } from "@funstack/ui/separator";
<label htmlFor="code">Verification code</label>
<OTPField.Root length={6} completeAction={verifyCode}> {/* div, position: relative */}
<OTPField.Input id="code" /> {/* input autocomplete=one-time-code, covers the Root */}
<OTPField.Slot index={0} /> {/* span aria-hidden: one character */}
<OTPField.Slot index={1} />
<OTPField.Slot index={2} />
<Separator decorative orientation="vertical" />
<OTPField.Slot index={3} />
<OTPField.Slot index={4} />
<OTPField.Slot index={5} />
</OTPField.Root>index and is aria-hidden. You choose the grouping with ordinary elements between them. A missing or repeated index is a development warning.Label part: name the Input with a <label for>, Field.Label, or aria-label (an unnamed Input is a development warning). No hidden input either: the Input is the form control.| onValueChange | completeAction | |
|---|---|---|
| Called | For every change of the filtered text: an edit ("activate"), a form reset, text found at hydration, a WebOTP fill ("platform"). | Each time an edit (or a WebOTP fill) leaves the code complete. Before it, onValueChange for the same edit. |
| Lane | Urgent: synchronously in the input event, outside any transition. A controlled parent's setCode(next) keeps the input in step per keystroke. | The Root's transition, awaited. |
| Pending | Never. | data-pending on the Root and the Input until every run has settled. The input stays enabled and editable. |
| Errors | A throw or a rejected promise goes to reportError; the edit stands. | A rejection reaches the nearest Error Boundary. A wrong code is not an error: resolve and show the message. |
completeAction runs for every completed code: a second one while the first is pending runs too (it is a different code), and so does the same code pasted again (the way to retry). A character the filter drops does not re-run it. There is no whilePending: ignoring a completion would drop what the user typed. An action that must not act on a stale code compares it with the current text after its await, as the example does.value you changed, for a form reset, or while disabled / readOnly.setCode("") in the action, after its await. That is an urgent update, which is what a text input needs.The browser performs every edit; in each input event the library reads the result and, where the filtered text differs, writes it back with the caret. Nothing is preventDefault()ed.
charset are dropped, so a pasted 123 456 or 123-456 becomes 123456. Full-width digits (from a Japanese or Chinese IME) are converted for "numeric". Case is kept.maxlength: it would cut 123 456 to 123 45 before the filter sees it. The length is the filter's, and the derived pattern's without JavaScript.compositionend. Numeric keyboards do not compose.OTPField.Root| Prop | Type | Default | Description |
|---|---|---|---|
length | number | – | Required. The number of characters in a complete code; also the pattern's count. A non-positive or fractional value logs a development warning. |
charset | "numeric" | "alphanumeric" | "alphabetic" | "numeric" | Which characters the filter keeps (ASCII digits, letters and digits, letters), and so the Input's inputmode (numeric / text) and pattern ([0-9]{6}, [A-Za-z0-9]{6}, [A-Za-z]{6}). |
value | string | – | Controlled text. It follows the input and cannot hold an edit back; a value the filter would change is rendered filtered, with a development warning. |
defaultValue | string | "" | Initial text in uncontrolled mode (filtered); also the form-reset target. |
onValueChange | UrgentChangeHandler<string, OTPFieldValueChangeDetails> | – | The text changed. A fact: called synchronously, outside any transition, not awaited. Called before completeAction for the same edit. |
completeAction | Action<[value: string, details: OTPFieldCompleteDetails & Rejectable]> | – | An edit left the code complete. Runs in the Root's transition and is awaited, with data-pending. May be a Server Function. |
submitOnComplete | boolean | false | Submit the Input's form (requestSubmit()) when an edit leaves the code complete, right after dispatching completeAction; inside a Field after re-validating the filtered text; during an IME composition at compositionend. See Auto-submit for the notice it needs. |
name, form | string | – | On the Input, which posts the text. name defaults to the Field's inside a Field.Root. |
required | boolean | false | On the Input: an empty field is valueMissing. Or the Field's. |
disabled | boolean | false | Native disabled on the Input, or the enclosing Field.Root's; never dispatches. A disabled field is not submitted. |
readOnly | boolean | false | Native readonly on the Input, or the enclosing Field.Root's: no edits and no completion; data-readonly on the Root and the Input. The code is focusable and submitted. Text the browser restored at hydration is put back, not adopted. |
dir | string | "ltr" | The native attribute, with a library default: a code is read left to right in every locale, so the Slots, the text and the caret keys stay left to right inside an RTL page. Your value (rtl, auto) wins, on the Root or on a render element. See Right-to-left pages. |
experimental_webOTP | boolean | false | Ask the browser for the code of an origin-bound SMS while the Input is mounted (WebOTP). Chromium and Safari; does nothing in Firefox. |
className | string | ((state: OTPFieldState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: OTPFieldState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: OTPFieldState) => ReactNode) | – | The parts. The function form receives the state. |
render | ReactElement | ((props, state: OTPFieldState) => ReactNode) | – | Replace the default <div> (element form) or take over rendering (function form). |
OTPFieldState (aliased as OTPFieldRootState and OTPFieldInputState) is { value, length, complete, pending, disabled, readOnly, invalid, required }: value is the filtered text, complete is value.length === length, pending is a completeAction in flight, invalid an error shown by an enclosing Field (false outside one), required the prop or the Field's.data-complete, data-pending, data-disabled, data-readonly, data-invalid (inside a Field), and position in style (relative) unless your style sets it. dir defaults to "ltr"; yours wins.Both details objects are { reason, event }; completeAction's also has valid, false only when the Field's validate rejects the code (see details.valid). onValueChange: "activate" for an edit (event is the input event, or the compositionend that ended a composition), "platform" for a form reset (the reset event), text found at hydration and a WebOTP fill (undefined). completeAction: "activate" for an edit, "platform" for a WebOTP fill. Serialisable: a Server Function receives { reason } ({ reason, valid } for completeAction).
OTPField.Input| Prop | Type | Default | Description |
|---|---|---|---|
autoComplete, inputMode, autoCapitalize, autoCorrect, spellCheck | string, string, string, string, boolean | "one-time-code", from charset, "off", "off", false | Defaults your own prop replaces. autoComplete="off" is the spelling for a PIN that is not a one-time code. |
className | string | ((state: OTPFieldState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: OTPFieldState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
render | ReactElement | ((props, state: OTPFieldState) => ReactNode) | – | Replace the default <input> (element form) or take over rendering (function form). |
OTPFieldState.type ("text"), value, pattern, name, form, required, disabled, readOnly, onChange (and native beforeinput, composition, selection and click listeners), the inline style (position: absolute; inset: 0; …; color: transparent; caret-color: transparent; forced-color-adjust: none; your style cannot override those keys), inside a Field id, aria-describedby (token-merged) and aria-invalid, and data-complete, data-pending, data-disabled, data-readonly, data-invalid.id, aria-label, aria-describedby, autoFocus, title and the rest go on the Input. A title is appended to the browser's message for a partial code. The outline is not touched: the Input's focus ring surrounds the whole field unless you move it.
OTPField.Slot| Prop | Type | Default | Description |
|---|---|---|---|
index | number | – | Required. Which character position this slot shows, from 0. |
className | string | ((state: OTPFieldSlotState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: OTPFieldSlotState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: OTPFieldSlotState) => ReactNode) | – | Default: the character, or nothing. A function draws a placeholder, a dot, a caret element. |
render | ReactElement | ((props, state: OTPFieldSlotState) => ReactNode) | – | Replace the default <span> (element form) or take over rendering (function form). |
OTPFieldSlotState is OTPFieldState plus { index, char, filled, active }: char is the character at index or null, active is the caret or part of the selection at this position while the input is focused.aria-hidden, data-index, data-filled, data-active, and pointer-events: none in the inline style.| Attribute | On | Meaning |
|---|---|---|
data-complete | Root, Input | The text has length characters. |
data-pending | Root, Input | A completeAction is in flight. |
data-disabled | Root, Input | Disabled (own prop or the Field's). |
data-readonly | Root, Input | Read-only (own prop or the Field's). |
data-invalid | Root, Input | Inside a Field that shows an error. |
data-index | Slot | The slot's index. |
data-filled | Slot | A character is at this position. |
data-active | Slot | The input is focused and the caret (the next character goes here) or part of the selection is at this position; at the end of a complete code, the last slot. |
:focus-visible, :user-invalid, :disabled | Input | The platform's own states (.root:has(:focus-visible)). |
.otp { display: inline-flex; gap: .5rem; }
.otp-input { border-radius: .5rem; font-size: 1rem; } /* 16px or more: no zoom on focus in iOS */
.otp-input::selection { background: transparent; }
.otp-slot { display: grid; place-items: center; inline-size: 2.5rem; block-size: 3rem;
border: 1px solid var(--line); border-radius: .5rem; font: 600 1.25rem / 1 var(--mono); }
.otp-slot[data-active] { border-color: var(--accent); }
.otp-slot[data-active]:not([data-filled])::after { /* the drawn caret */
content: ""; inline-size: 1px; block-size: 1.25em; background: currentColor;
animation: otp-caret 1s steps(1) infinite;
}
@keyframes otp-caret { 50% { opacity: 0; } }
.otp[data-pending] .otp-slot { opacity: .6; }
.otp[data-invalid] .otp-slot { border-color: var(--danger); }
.otp-slot:not([data-filled])::before { content: "·"; color: var(--muted); } /* placeholder */
@media (prefers-reduced-motion: reduce) { .otp-slot::after { animation: none; } }pointer-events: none, so a dimmed, positioned or animated Slot never takes the click from the Input..otp:has(.otp-input:focus-visible) .otp-slot[data-active].forced-color-adjust: none); the Slots are ordinary text and follow the system colours.| Key | Behaviour |
|---|---|
A character of charset | Inserted, or typed over the character at the caret. Others are dropped. |
| Backspace / Delete | Native: the character before / after the caret; the rest closes up. |
| ArrowLeft / ArrowRight / Home / End (with Shift: select) | Native caret movement: one character is one slot. |
| Ctrl+A / Cmd+A (also C, X, V, Z) | Native select all, copy, cut, paste and undo. |
| Enter | Native implicit submission of the form. |
| Click | Focuses the Input and puts the caret at the slot under the pointer. |
pattern alone tells a screen-reader user nothing until it fails.data-pending). The answer is your content: a Field error through aria-describedby and the Form's focus move, or your own role="status" message, as in the example.A one-time code is read left to right in Arabic and Hebrew too, so OTPField.Root renders dir="ltr" unless you pass dir. Inside a dir="rtl" page Slot 0 stays the leftmost box, ArrowLeft moves to the previous character, and your logical CSS (margin-inline-start, a separator between groups) inside the Root resolves as left to right. The label, the description and the error message are outside the Root and follow the page. The attribute is in the server HTML, so it holds before hydration.
Without it the boxes would mirror (Slot 0 at the right) while the one input's text stays a left-to-right run, and the engines disagree on which way the arrow keys then move the caret. Pass dir="rtl" only for a code that really is read right to left; there is no value meaning "follow the page". More in Direction and locales.
Concept: Transitions & ViewTransition
Each completeAction run: fsui-otp-field plus fsui-otp-field-complete. Typing is urgent and carries none. No part takes a transition prop; use the types in your own boundary (the next step of a sign-in).
::view-transition-old(.step):active-view-transition-type(fsui-otp-field-complete) { animation: slide-out-left .2s; }Concept: Pending & optimistic state
Nothing is optimistic: the text is urgent library state written from the input event. data-pending is on the Root and the Input while a completeAction runs; the field is never disabled meanwhile.
Concept: Suspense
Nothing specific: the OTPField renders no content region.
Concept: Browser-owned state
The text is the input's: the browser edits it, the library filters it. A form reset is the browser's; the library adopts the reset target with onValueChange ("platform") and runs no completion. The selection is the browser's too; the Slots mirror it (data-active).
Concept: Server Components
The server HTML is the input and the Slots with the default value. Before hydration the input takes typing, paste and autofill natively, but the text is transparent and the Slots are static, so what is typed is not visible until hydration. At hydration the text is filtered and adopted ("platform"), with no completion: the user submits with Enter or the button. A form submitted before hydration posts the text, checked by pattern.
The Slots never fill without script. A page that must work without it shows the plain input instead (the inline styles need !important to undo):
@media (scripting: none) {
.otp-slot { display: none; }
.otp-input { position: static !important; color: inherit !important; caret-color: auto !important;
border: 1px solid var(--line) !important; padding: .5rem !important; }
}name; a partial code posts as typed, and pattern blocks the submission (patternMismatch). required makes an empty one valueMissing.defaultValue uncontrolled, the mount-time value controlled) with onValueChange "platform", and runs no completion."use client";
import { useActionState } from "react";
import { Field } from "@funstack/ui/field";
import { Form } from "@funstack/ui/form";
import type { FormErrors } from "@funstack/ui/form";
import { OTPField } from "@funstack/ui/otp-field";
import { sleep } from "./fake-api.js";
const SLOTS = [0, 1, 2, 3, 4, 5];
interface VerifyState {
readonly errors?: FormErrors;
readonly signedIn?: boolean;
}
// A pretend Server Function: it checks the code and returns a field error for a wrong one.
async function verify(_prev: VerifyState, formData: FormData): Promise<VerifyState> {
await sleep(900);
if (formData.get("code") !== "123456") {
return { errors: { code: "That code has expired. We sent you a new one." } };
}
return { signedIn: true };
}
// The code is submitted as soon as it is complete (`submitOnComplete`): the form's pending
// shows on the button, a wrong code comes back as the Field's error with focus on the input,
// and the next keystroke dismisses it. The description says so before the field (WCAG 3.2.2),
// and the button stays for a user who wants to check the code first. Try 111111, then 123456.
export function OTPFieldAutoSubmit() {
const [state, formAction] = useActionState(verify, {});
if (state.signedIn === true) {
return <p className="demo-readout">Signed in.</p>;
}
return (
<Form.Root action={formAction} errors={state.errors} className="demo-form">
<Field.Root name="code" required className="demo-fieldset">
<Field.Label className="demo-label">Sign-in code</Field.Label>
<Field.Description className="demo-description">
The 6-digit code from your authenticator app. It is submitted when complete.
</Field.Description>
<OTPField.Root length={6} submitOnComplete className="demo-otp">
<OTPField.Input className="demo-otp-input" title="6 digits" />
{SLOTS.map((i) => (
<OTPField.Slot key={i} index={i} className="demo-otp-slot" />
))}
</OTPField.Root>
<Field.Error className="demo-field-error">
{({ validity, messages }) =>
validity.patternMismatch ? "Enter all 6 digits." : messages.join(" ")
}
</Field.Error>
</Field.Root>
<div className="demo-row">
<Form.Submit className="demo-button demo-primary demo-submit">
{({ pending }) => (
<>
{pending && <span className="demo-spinner" aria-hidden />}
Verify
</>
)}
</Form.Submit>
</div>
</Form.Root>
);
}/* OTPField: the Root is the box, the Input covers it with transparent text (the library's inline
style), and the Slots draw the characters, the caret and the focus. */
.demo-otp-form {
display: grid;
gap: 0.35rem;
justify-items: start;
}
.demo-otp {
display: inline-flex;
gap: 0.4rem;
border-radius: 8px;
}
.demo-otp-input {
border-radius: 8px;
/* 16px or more: iOS does not zoom on focus. */
font-size: 1rem;
outline: none;
}
.demo-otp-input::selection {
background: transparent;
}
/* The focus ring is drawn on the row while the input has keyboard or pointer focus. */
.demo-otp:has(.demo-otp-input:focus-visible) .demo-otp-slot[data-active] {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
.demo-otp-slot {
display: grid;
place-items: center;
inline-size: 2.5rem;
block-size: 3rem;
border: 1px solid var(--color-border);
border-radius: 8px;
background: var(--color-bg);
color: var(--color-text);
font:
600 1.25rem / 1 ui-monospace,
monospace;
font-variant-numeric: tabular-nums;
}
.demo-otp-slot[data-active] {
border-color: var(--color-primary);
}
/* The drawn caret in an empty active slot. */
.demo-otp-slot[data-active]:not([data-filled])::after {
content: "";
inline-size: 1px;
block-size: 1.25em;
background: currentColor;
animation: demo-otp-caret 1s steps(1) infinite;
}
@keyframes demo-otp-caret {
50% {
opacity: 0;
}
}
.demo-otp[data-pending] .demo-otp-slot {
opacity: 0.6;
}
.demo-otp[data-pending] .demo-otp-input {
cursor: progress;
}
.demo-otp[data-invalid] .demo-otp-slot {
border-color: #dc2626;
}
.demo-otp-done {
display: grid;
gap: 0.5rem;
justify-items: start;
}
@media (prefers-reduced-motion: reduce) {
.demo-otp-slot::after {
animation: none;
}
}
/* Without JavaScript the Slots never fill: show the plain input instead. */
@media (scripting: none) {
.demo-otp-slot {
display: none;
}
.demo-otp-input {
position: static !important;
color: inherit !important;
caret-color: auto !important;
border: 1px solid var(--color-border) !important;
padding: 0.5rem !important;
}
}Field.Root the Input is the Field's control, as Field.Control is: Field.Label's for names it, the description and error describe it, its validity (required, the derived pattern, validate, server errors) is the input's own. There is no hidden input: the text shown is the value posted.Form.Submit and the Field parts show data-pending, a wrong code comes back in errors and is shown by Field.Error with focus on the Input, and the next keystroke dismisses it. completeAction is for a field with no form around it.validate on the filtered text and dismisses a server error); a reset or a controlled change re-runs validate only.autocomplete="one-time-code" is what iOS, Android keyboards and password managers key on, and it needs nothing from the library. WebOTP is the API form of the same thing for SMS: the page asks for the code of a message whose last line names its origin (@example.com #123456), the browser asks the user, and a promise resolves with the code. It is in Chromium and Safari, not in Firefox, so it is behind experimental_webOTP.
OTPCredential present, the Input's mount requests a code. A resolved code of exactly length characters (after the filter) fills the field (onValueChange "platform") and completes it (completeAction "platform", submitOnComplete). Anything else, a refusal, and an abort are ignored.// A Server Function as the check, straight from a Server Component:
<OTPField.Root length={6} completeAction={verifyCode} experimental_webOTP>…</OTPField.Root>