# One-time code

Boxes for a one-time verification code, with paste, autofill and a resend cooldown.

- Family: form
- Import: `import { OtpField } from "@senvenli/react/form";`
- Page: https://design.senvenli.com/docs/components/otp-field
- JSON: https://design.senvenli.com/docs/components/otp-field.json

## Example: A six-digit code

One real input, so a pasted or autofilled code fills every box; `onComplete` runs on the last digit.

```tsx
import { Text } from "@senvenli/react/display";
import { OtpField } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";
import { useState } from "react";

export default function Example() {
  const [code, setCode] = useState<string | null>(null);
  return (
    <Stack space="space-150">
      <OtpField
        label="Verification code"
        description="We sent a 6-digit code to ada@example.com."
        onChange={() => setCode(null)}
        onComplete={setCode}
      />
      {code && <Text size="body-small" tone="subtle">Checking {code}…</Text>}
    </Stack>
  );
}
```

## Examples

### Four digits with resend

The field takes the code; a Button with `useCooldownAction` sends it again after a wait.

```tsx
import { Button } from "@senvenli/react/action";
import { Text } from "@senvenli/react/display";
import { useCooldownAction } from "./use-cooldown-action";
import { OtpField } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";

// The field takes the code; "Send again" is a Button with useCooldownAction, which waits after each send and starts
// no wait (and says so) when a send fails.
export default function Example() {
  // The first code was just sent, so the 30-second wait is already running.
  const resend = useCooldownAction(() => new Promise((done) => setTimeout(done, 800)), 30, 30);
  return (
    <Stack space="space-150">
      <OtpField label="Code from your text message" length={4} description="Sent to the number ending in 0132." />
      <Stack space="space-050">
        <div>
          <Button size="small" variant="subtle" isDisabled={resend.remaining > 0} isPending={resend.isPending} onPress={() => void resend.run()}>
            {resend.remaining > 0 ? `Send again in 0:${String(resend.remaining).padStart(2, "0")}` : "Send again"}
          </Button>
        </div>
        <span role="status">{resend.failed && <Text size="body-small" tone="danger">The code was not sent. Try again.</Text>}</span>
      </Stack>
    </Stack>
  );
}
```

### A wrong code

The error says what to do next.

```tsx
import { OtpField } from "@senvenli/react/form";

export default function Example() {
  return (
    <OtpField
      label="Verification code"
      defaultValue="482917"
      isInvalid
      errorMessage="Wrong code. Enter the latest code from your email."
    />
  );
}
```

## Guidelines

### When to use it

- Entering a code sent by text message or email.

### Use something else when

- [input](https://design.senvenli.com/docs/components/input.md): The code is long, mixed or pasted from elsewhere, with `type="number"` or text.

## Accessibility

Built in:

- One input under the boxes, so autofill and screen readers see a single field.
- The resend countdown is announced.

You provide:

- A label that says where the code was sent.

## API reference

### OtpField

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| label | `React.ReactNode` |  | yes |  |
| length | `4 \| 6` |  | no | 4 or 6 digits; 6 splits 3 + 3 with a dash. |
| description | `React.ReactNode` |  | no |  |
| errorMessage | `React.ReactNode` |  | no | Say what to do: "Wrong code. Enter the latest code from your phone." |
| onComplete | `(code: string) => void` |  | no | Called once the last digit is entered (submit there). |
| requiredValidation | `RequiredValidation` |  | no | Who says an empty required field is missing: `field` (default) or `app`. With `app` a DS Form's `onSubmit` runs with the field empty, and the app's own error must clear on change. See {@link RequiredValidation} for the whole contract. |
| motion | `ComponentMotion` |  | no | `auto` (follow the device), `reduce` or `none`, for this component; the provider's setting otherwise. |

Behavior props from React Aria:

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| defaultValue | `string` |  | no | The default value (uncontrolled). |
| autoFocus | `boolean` |  | no | Whether the element should receive focus on render. |
| enterKeyHint | `"enter" \| "done" \| "go" \| "next" \| "previous" \| "search" \| "send"` |  | no | An enumerated attribute that defines what action label or icon to preset for the enter key on virtual keyboards. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/enterkeyhint). |
| spellCheck | `string` |  | no | An enumerated attribute that defines whether the element may be checked for spelling errors. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck). |
| autoCorrect | `string` |  | no | An attribute that takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autocomplete). |
| onCopy | `ClipboardEventHandler<HTMLInputElement>` |  | no | Handler that is called when the user copies text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncopy). |
| onCut | `ClipboardEventHandler<HTMLInputElement>` |  | no | Handler that is called when the user cuts text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncut). |
| onPaste | `ClipboardEventHandler<HTMLInputElement>` |  | no | Handler that is called when the user pastes text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste). |
| onCompositionEnd | `CompositionEventHandler<HTMLInputElement>` |  | no | Handler that is called when a text composition system completes or cancels the current text composition session. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionend_event). |
| onCompositionStart | `CompositionEventHandler<HTMLInputElement>` |  | no | Handler that is called when a text composition system starts a new text composition session. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionstart_event). |
| onCompositionUpdate | `CompositionEventHandler<HTMLInputElement>` |  | no | Handler that is called when a new character is received in the current text composition session. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionupdate_event). |
| onFocus | `(e: FocusEvent<HTMLInputElement, Element>) => void` |  | no | Handler that is called when the element receives focus. |
| onBlur | `(e: FocusEvent<HTMLInputElement, Element>) => void` |  | no | Handler that is called when the element loses focus. |
| onChange | `(value: string) => void` |  | no | Handler that is called when the value changes. |
| onBeforeInput | `FormEventHandler<HTMLInputElement>` |  | no | Handler that is called when the input value is about to be modified. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event). |
| onInput | `FormEventHandler<HTMLInputElement>` |  | no | Handler that is called when the input value is modified. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event). |
| onSelect | `ReactEventHandler<HTMLInputElement>` |  | no | Handler that is called when text in the input is selected. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event). |
| isDisabled | `boolean` |  | no | Whether the input is disabled. |
| onFocusChange | `(isFocused: boolean) => void` |  | no | Handler that is called when the element's focus status changes. |
| form | `string` |  | no | The `<form>` element to associate the input with. The value of this attribute must be the id of a `<form>` in the same document. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form). |
| name | `string` |  | no | The name of the input element, used when submitting an HTML form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefname). |
| value | `string` |  | no | The current value (controlled). |
| excludeFromTabOrder | `boolean` |  | no | Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available. |
| isRequired | `boolean` |  | no | Whether user input is required on the input before form submission. |
| isReadOnly | `boolean` |  | no | Whether the input can be selected but not changed by the user. |
| isInvalid | `boolean` |  | no | Whether the value is invalid. |
| validate | `(value: string) => true \| ValidationError \| null \| undefined` |  | no | A function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if `validationBehavior="native"`. For realtime validation, use the `isInvalid` prop instead. |
| validationBehavior | `"aria" \| "native"` |  | no | Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA. |
| minLength | `number` |  | no | The minimum number of characters required by the input. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefminlength). |
| pattern | `string` |  | no | Regex pattern that the value of the input must match to be valid. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefpattern). |

Also takes 84 standard DOM and ARIA attributes (id, aria-label, event handlers…).

### Tokens it reads

`--ds-background-disabled`, `--ds-background-input`, `--ds-background-input-hovered`, `--ds-background-neutral-pressed`, `--ds-background-neutral-subtle-hovered`, `--ds-border`, `--ds-border-bold`, `--ds-border-danger`, `--ds-border-focused`, `--ds-easing-enter`, `--ds-easing-standard`, `--ds-icon-subtle`, `--ds-radius-control-medium`, `--ds-radius-full`, `--ds-radius-medium`, `--ds-radius-small`, `--ds-size-control`, `--ds-size-control-compact`, `--ds-size-control-large`, `--ds-size-icon`, `--ds-space-050`, `--ds-space-075`, `--ds-space-100`, `--ds-space-150`, `--ds-space-200`, `--ds-surface-sunken`, `--ds-text`, `--ds-text-danger`, `--ds-text-disabled`, `--ds-text-subtle`, `--ds-text-subtlest`

## Related

- [input](https://design.senvenli.com/docs/components/input.md)
