useVerificationInputs
Helps with verification input features
const [inputRefs, getValues] = useVerificationInputs(options)
Usage
Basic:
const Component = () => {
const focusRef = React.useRef();
const [inputRefs, getValues] = useVerificationInputs({
focusAfter: focusRef,
lastInputCallback: () => {
console.log('lastInputCallback executed');
},
});
return (
<>
{Array.from({ length: 6 }, (_, i) => `item-${i}`).map((item, i) => (
<>
<label htmlFor={item} style={srOnly}>
{item}
</label>
<input
id={item}
key={item}
ref={(input) => (inputRefs.current[i] = input)}
style={defaultStyles}
type='text'
/>
</>
))}
<button onClick={() => console.log(getValues())} ref={focusRef} type='button'>
Get Values
</button>
</>
);
};
Forwarding ref
to a component:
const InputComponent = React.forwardRef((props, ref) => <input ref={ref} {...props} />);
const Component = () => {
const focusRef = React.useRef();
const [inputRefs, getValues] = useVerificationInputs({
focusAfter: focusRef,
lastInputCallback: () => {
console.log('lastInputCallback executed');
},
});
return (
<>
{Array.from({ length: 6 }, (_, i) => `item-${i}`).map((item, i) => (
<>
<label htmlFor={item} style={srOnly}>
{item}
</label>
<InputComponent
id={item}
key={item}
ref={(input) => (inputRefs.current[i] = input)}
style={defaultStyles}
type='text'
/>
</>
))}
<button onClick={() => console.log(getValues())} ref={focusRef} type='button'>
Get Values
</button>
</>
);
};
Arguments
Accepts an object of options
Name | Type | Required? |
---|---|---|
focusAfter | React.MutableRefObject | ❌ |
lastInputCallback | () => void | ❌ |
shouldFocusFirst | boolean | ❌ |
Returns
Index | Description | Type |
---|---|---|
0 | ref defaulted to an empty array | React.MutableRefObject<HTMLInputElement[]> |
1 | Function that gets values from the referenced inputs | () => [string] |