devfolioco / react-otp-input

:heavy_check_mark: OTP Input Component for React
http://devfolioco.github.io/react-otp-input
MIT License
643 stars 423 forks source link

fix: Values always added from first input even when another input is selected or focused #448

Closed ahmed-s-fatahallah closed 4 days ago

ahmed-s-fatahallah commented 2 months ago

Replaced the const getOTPValue = () => (value ? value.toString().split('') : []); function with useRef hook to save the state of the current otp array to match each input box with its index of the array to fix the issue of when adding new value it always starts from the first input box even when another input is selected or focused.

Also, add an if check to check at each rerender if the value is empty string then reset the value of the otp array.

if (value.trim() === '') {
    otpValueRef.current = Array(numInputs);
  }

Moreover, removed the activeInput subtract from numInputs in

const pastedData = event.clipboardData
      .getData('text/plain')
      .slice(0, numInputs - activeInput)
      .split('');

and removed the check for pos >= activeInput in

if (pos >= activeInput && pastedData.length > 0) {
        otp[pos] = pastedData.shift() ?? '';

to make pasting start from the first input even if any other input is selected or focused

PS: I don't know if the copy paste behavior for always starting from the first input is intended or not but I felt that it make sense to paste the whole copied string across all the input not just starting from selected one.

ygag-anase commented 1 week ago

@ahmed-s-fatahallah Thank you for this PR. It fixed the issue. but after this code change I'm facing a issue with auto filling SMS OTP in Chrome browser of iOS and Android. The value will be there but it won't be visible in the input field. suppose the SMS OTP is received and if we tap on otp number on the keyboard clipboard, the otp field will be empty, but the value will be available in the state, If we click proceed, the form will be submitted with the otp we took from the clipboard. I tested after removing your changes and it works well as expected. do you get any idea about this issue? Once again I really appreciating your work, Thanks alot.

ahmed-s-fatahallah commented 4 days ago

Thanks for your reply, I didn't notice this bug, I will look into it and submit a new PR when I fix it.