react-otp-input icon indicating copy to clipboard operation
react-otp-input copied to clipboard

When OTP is wrong I want to set focus on first input

Open Jayrathod1234 opened this issue 1 year ago • 1 comments

In the current implementation of the OTP input component, when a user submits an incorrect OTP, the focus remains on the last input field (input tab 6) instead of resetting to the first input field (input tab 1). This behavior can confuse users, as they may need to start over but find themselves unable to easily re-enter their OTP without manually clicking on the first input.

Jayrathod1234 avatar Oct 03 '24 12:10 Jayrathod1234

I don't know if this is still an issue for you, because it has been some time, but I found a solution to this:

type OTPInputRef = {focus: (index: number) => void};

export const EnhancedOTPInput = forwardRef<OTPInputRef, OTPInputProps>(
  (props, ref) => {
    const [inputRefs] = useState<{[key: number]: HTMLInputElement | null}>({});
    const focus = (pos: number) => inputRefs[pos]?.focus();

    useImperativeHandle(ref, () => ({focus}));

    return (
      <OTPInput
        {...props}
        renderInput={(inputProps, index) => (
          <input
            {...inputProps}
            ref={ref => {
              inputProps.ref(ref);
              inputRefs[index] = ref;
            }}
          />
        )}
      />
    );
  }
);

You can then do this:

const inputRef = useRef<OTPInputRef>(null);

useEffect(() => {
  inputRef.current?.focus(0); // 0 for first input, 1 for second etc...
}, [someDependency]);

return <EnhancedOTPInput ref={inputRef} />;

Hope this helps

DieserMerlin avatar Jan 06 '25 19:01 DieserMerlin