useInputOtp
Hook that manages OTP input state, focus navigation, and keyboard handling.
basic-demo
Usage#
import { useInputOtp } from '@primereact/headless/inputotp';
const { rootProps, getTextProps } = useInputOtp();
return (
<div {...rootProps}>
<input {...getTextProps(0)} />
<input {...getTextProps(1)} />
<input {...getTextProps(2)} />
<input {...getTextProps(3)} />
</div>
);useInputOtp manages OTP value state, per-input focus navigation, and keyboard/paste handling — see Primitive for a component-based API.
Features#
- Returns spread-ready
rootPropswith ref callback and per-indexgetTextPropsfor each input slot - DOM-based input detection via
rootProps.ref— the hook queries inputs within the root element automatically - Automatic focus navigation between inputs on type, delete, and arrow keys
- Clipboard paste support that distributes characters across inputs
- Controlled and uncontrolled value management via
value/defaultValue
Behavior#
Integer Only#
Set integerOnly to restrict input to numeric characters. The hook sets inputMode to "numeric" and blocks non-digit keystrokes.
const { rootProps, getTextProps } = useInputOtp({ integerOnly: true });Mask#
Set mask to obscure input values. The hook sets type to "password" on each input.
const { rootProps, getTextProps } = useInputOtp({ mask: true });Controlled#
Pass value and onValueChange for controlled usage.
const [value, setValue] = React.useState('');
const { rootProps, getTextProps } = useInputOtp({
value,
onValueChange: (e) => setValue(e.value)
});Custom Styling with Data Attributes#
The root element includes data-scope="inputotp" and data-part="root". Each input includes data-scope="inputotp" and data-part="input".
[data-scope='inputotp'][data-part='root'] {
display: flex;
gap: 0.5rem;
}
[data-scope='inputotp'][data-part='input'] {
width: 2.5rem;
text-align: center;
}
[data-scope='inputotp'][data-part='input']:focus {
border-color: var(--p-primary-color);
}API#
useInputOtp#
| Name | Type | Default |
|---|---|---|
value | string | — |
| Specifies whether a inputotp should be checked or not. | ||
defaultValue | string | — |
| Specifies whether a inputotp should be checked or not. | ||
integerOnly | boolean | false |
| When present, it specifies that only integers are allowed. | ||
mask | boolean | false |
| Mask pattern. | ||
disabled | boolean | undefined |
| When present, it specifies that the component should be disabled. | ||
onValueChange | (event: useInputOtpValueChangeEvent) => void | — |
| Callback to invoke when value changes. | ||
Accessibility#
See InputOtp Primitive for WAI-ARIA compliance details and keyboard support.