packages
useVerificationInputs

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

NameTypeRequired?
focusAfterReact.MutableRefObject
lastInputCallback() => void
shouldFocusFirstboolean

Returns


IndexDescriptionType
0ref defaulted to an empty arrayReact.MutableRefObject<HTMLInputElement[]>
1Function that gets values from the referenced inputs() => [string]