# Otp

Headless, unstyled one-time-code input, one `input` per character over a single string value. Typing advances focus, `Backspace` walks back, and a paste or SMS autofill fills every slot. `Otp.useOtp()` reads the value and the slot list inside the root.

## Use for

- entering a verification code sent by SMS or email
- an authenticator (TOTP) code field
- a fixed-length PIN split into one box per character

## Practices

- Do: Render one `Otp.Input` per entry in `Otp.useOtp().slots`, keyed and indexed by `slot.index`.
- Do: Name the field with `aria-label` or `aria-labelledby` on `Otp.Root`, or a `<label>` for its `id`.
- Do: Pass `name` to submit the code from a plain `<form>`.
- Don't: Use it directly in a feature. Use the styled `Otp` in `src/components/otp/`, or `VerificationCode` in `src/blocks/verification/` for a code step.
- Don't: Pass `id` or `aria-label` to the first `Otp.Input`. It takes both from the root.

## API reference

### Otp.Root

Owns the value and focus, and renders a `div` with `role="group"`. Carries `data-empty`, `data-complete` and `data-disabled`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `length` | `number` |  | The number of slots. |
| `value` | `string` |  | The code, when controlled. |
| `defaultValue` | `string` | `''` | The code on mount, when uncontrolled. |
| `onValueChange` | `(value: string) => void` |  | Called with the full value on every change. |
| `onComplete` | `(value: string) => void` |  | Called once when the last slot fills. |
| `pattern` | `OtpPattern` | `'numeric'` | The allowed characters. Others and whitespace are stripped. |
| `mask` | `boolean` | `false` | Renders slots as password inputs. |
| `name` | `string` |  | Submits the value through a hidden input under this name. |
| `disabled` | `boolean` | `false` | Disables every slot. |
| `focusableWhenDisabled` | `boolean` | `false` | Keeps disabled slots focusable as read-only and `aria-disabled`. |
| `required` | `boolean` | `false` | Marks every slot required, so a partial code fails form validation. |
| `id` | `string` |  | Lands on the first slot, so a `<label>` can target it. Later slots take `${id}-2` and on. |

### Otp.Input

One character slot, as an `input` with a roving tab index. Carries `data-active`, `data-filled` and `data-disabled`. Focus snaps back to the first empty slot.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `index` | `number` |  | The slot position, from `slot.index`. |

## Examples

### Six-digit code

```tsx
<Otp.Root length={6} aria-label='Verification code' onComplete={submit}>
  <Slots />
</Otp.Root>

function Slots() {
  const { slots } = Otp.useOtp();
  return slots.map(slot => <Otp.Input key={slot.index} index={slot.index} />);
}
```

## Related

- `VerificationCode`
