Code input

Slant / Controls

One-time-code entry with auto-advance, paste and a completion callback.

Demo

Verification code

Usage

@tuttn/slant
import { CodeInput } from '@tuttn/slant'

// Uncontrolled: it keeps its own code, and a name submits it with the form.
<form action="/verify">
  <CodeInput name="code" onComplete={code => verify(code)} />
</form>

// Controlled: the code is a string, a space for each empty box inside it.
const [code, setCode] = useState('')
<CodeInput value={code} onValueChange={setCode} invalid={rejected} />

// A shorter code with its own labels.
<CodeInput length={4} label="PIN" digitLabel={index => `PIN digit ${index + 1}`} />

Props

PropTypeDefaultDescription
lengthnumber6Number of boxes.
valuestring—The code, one character per box: a space for an empty box inside the code, and trailing empty boxes left off ('12 4' fills boxes 1, 2 and 4). Pass it to control the input; leave it out and use `defaultValue` to let it keep its own.
defaultValuestring''The starting code when uncontrolled, in the same form as `value`.
onValueChange(value: string) => void—Called with the new code on every edit or paste, in the same form as `value`.
onComplete(code: string) => void—Called with the joined code once every box holds a digit.
namestring—Renders a hidden input with this name carrying the code, for a native form.
formstring—The id of the form the hidden input belongs to, when it sits outside that form.
invalidboolean—Marks every box as invalid (aria-invalid), e.g. after a rejected code. Inside a Field, the field's `invalid` does this.
disabledboolean—Disables every box; a disabled code is not submitted with its form.
labelstring'Verification code' (the root's `messages.verificationCode`)The group's accessible name.
digitLabel(index: number) => stringindex => `Digit ${index + 1}` (the root's `messages.digit`)The accessible name of each box, from its zero-based index.
autoFocusboolean—Focuses the first empty box on mount.
…restHTMLAttributes<HTMLDivElement>—className, style and other attributes go on the group element, which also takes the ref.

The value is a string with one character per box: a space stands for an empty box inside the code, and trailing empty boxes are left off, so '12 4' fills the first, second and fourth boxes. onComplete fires with the joined digits once every box holds one.

The first box asks for one-time-code autocompletion, so phones can fill it from a text message. The labels default to the root’s messages.verificationCode and messages.digit.

Full source