The usePinField hook provides the core logic and state management for a PIN input field. It returns a Handler object containing everything needed to synchronize multiple input elements with a single PIN value.
To use it, call usePinField() and destructure the returned properties. You will typically use refs to attach to your individual input elements, state to determine the status of each digit (like focus or error), and value to get the current full PIN string.
Returned Handler Object
| Property | Type | Description |
|---|
refs | RefObject<HTMLInputElement[]> | An array of refs to be attached to each individual PIN input element. |
state | State | The current state of the PIN field (e.g., length, values, cursor position). |
dispatch | ActionDispatch<[Action]> | A function to manually dispatch actions to the PIN field reducer. |
value | string | The current concatenated PIN value as a single string. |
setValue | (value: string) => void | A function to programmatically set the entire PIN value. |
Example Usage
import { usePinField } from 'react-pin-field';
function MyPinComponent() {
const { refs, state, value, setValue } = usePinField();
return (
<div>
<div style={{ display: 'flex', gap: '8px' }}>
{/* Create an input for each digit in the state length */}
{Array.from({ length: state.length }).map((_, index) => (
<input
key={index}
ref={(el) => (refs.current[index] = el!)}
value={state.values[index] || ''}
// ... other input props
/>
))}
</div>
<p>Current PIN: {value}</p>
</div>
);
}
import { usePinField } from 'react-pin-field';
function MyPinComponent() {
const { refs, state, value, setValue } = usePinField();
return (
<div>
<div style={{ display: 'flex', gap: '8px' }}>
{Array.from({ length: state.length }).map((_, index) => (
<input
key={index}
ref={(el) => (refs.current[index] = el!)}
value={state.values[index] || ''}
/>
))}
</div>
<p>Current PIN: {value}</p>
</div>
);
}