Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Jayrathod1234 opened this issue Oct 3, 2024 · 1 comment
Open

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

Jayrathod1234 opened this issue Oct 3, 2024 · 1 comment

Comments

@Jayrathod1234
Copy link

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.

@DieserMerlin
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants