devfolioco / react-otp-input

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

Backspace delete specific input field and stay on it #306

Closed emran-jatri closed 1 year ago

emran-jatri commented 3 years ago

Backspace delete specific input field and stay on it. I see many issues and pull requests in this git, but after solving this issue git and npm are not updated? I need solved things right now, can someone please help me with how to do that? when I click on backspace it should work like the delete button on the keyboard. thanks you

Joojo7 commented 2 years ago

@emran-jatri Did you find a solution to this?

blactrojan commented 2 years ago

Found out a way to fix this

import React, { useEffect, useRef, useState } from "react";
import OtpInput from "react-otp-input";

const App = () => {
  const [otp, setOtp] = useState();
  const [prevOtp, setPrevOtp] = useState()
  const otpRef = useRef(null);

  const handleChange = (e) => {
    setPrevOtp(otp)
    setOtp(e)
  };

  useEffect(()=>{
    if(otp?.length < prevOtp?.length)
      otpRef.current.focusInput(otp.length)
  },[otp])

  return (
    <>
      <OtpInput
        ref={otpRef}
        value={otp}
        onChange={handleChange}
        numInputs={6}
        separator={<span>-</span>}
      />
    </>
  );
};