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

Allow imperative calls to focus the otp input via ref

Open asenmitrev opened this issue 1 year ago • 3 comments

  • Describe the Feature Request A way to imperatively focus the code input at the active input position, rather than relying on just shouldAutoFocus.

Right now, to focus the input, one has to set shouldAutoFocus to true, as that internally focuses the first input. To focus again, one must reset shouldAutoFocus to false and then set it to true. There are many use cases where imperative calling of the focus() function might be required and this is a useful feature to have.

A separate problem is that this hack will only focus the input with index 0, not the activeInput.

  • Describe Preferred Solution We could use useImperativeHandle and pass a ref to the otp component, where we impement something like this:
useImperativeHandle(
  ref,
  () => ({
    focus() {
      inputRefs.current[activeInput]?.focus();
    },
  }),
  [activeInput],
);

If you consider this a viable solution I can open a PR with an implementation.

asenmitrev avatar Sep 28 '23 13:09 asenmitrev

Yeah @asenmitrev This makes sense can you open a PR for the same?

prateek3255 avatar Oct 01 '23 05:10 prateek3255

@prateek3255 here is the PR

asenmitrev avatar Oct 02 '23 07:10 asenmitrev

@prateek3255 would you say this will be reviewed and merged at some point?

asenmitrev avatar Oct 16 '23 07:10 asenmitrev