One-time Code
Square cells for a code sent by text, drawn over one real input, so pasting and autofill just work and a whole code lands a cell at a time.
Usage
import { OtpInput } from '@wdzyi/ui';
<OtpInput
label='Verification code'
hint='Sent by text to the number ending 21'
onComplete={async (code) => {
const { ok } = await verify(code);
return ok;
}}
/>Part of @wdzyi/ui. See setup to install it, or copy the code above.
Props
- lengthnumber = 6
- How many digits the code has. An even number from six up is split in two by a short dash.
- value, defaultValue, onValueChangestring, string, (value: string) => void
- Hold the digits yourself, or let the field hold them. Anything that isn’t a digit is dropped, and a bad code calls onValueChange with nothing once it clears.
- onComplete(code: string) => boolean | Promise<boolean>
- Called once with a whole code. Return whether it’s right, or a promise of it, and it says Verifying while it’s out. Without it, a whole code passes a second later, as a stand-in.
- labelstring = 'Verification code'
- Above the cells, and the field’s name for screen readers.
- hintstring
- Under the cells while it waits, such as where the code was sent.
- disabledboolean = false
- Faded, and it can’t be typed in.
- activeboolean = false
- Shows the caret in the next cell without focus, for a code typed on a keypad of your own.
- namestring
- Sent with a form, as the input’s value.
- classNamestring
- Added to its root. It’s 360px wide at most, and the cells narrow with the space it’s in.
Notes
- Each digit pops in from half its size on a spring over 340ms. A code that arrives at once, pasted or filled in from a message, lands a cell every 40ms. The caret blinks every 1.06s, and starts solid each time it moves.
- A whole code locks the field and is checked once. The cells go quiet as the last digit lands, and it says Verifying, with the pixels working, for at least 600ms. A good code turns the edges green from the left, 60ms a cell, each lifting 3px as the wave passes, and a green tick says Verified. A bad one shakes the row in a swing that dies away over 560ms, stays pink for 1.1s, then the digits go, the last first, 35ms apart.
- Underneath is one text input with the number pad and one-time-code autofill. It only ever adds at the end: the arrows don’t move the caret, Backspace steps back, Shift with the arrows selects digits to type over, and a paste keeps only the digits of whatever was copied, such as 482 917.
- It sends a key cue as each digit lands, typed or played back, and a pasted code sends one a cell, 40ms apart. Backspace sends erase, and the answer sends success or error. Screen readers hear the field by its label and hint, then Verifying the code, and Verified or why it failed.
- With reduced motion, nothing pops, lifts or shakes. The colours still change, and the line under the cells fades.