OTP Component - salimakhtar92/ReactJs GitHub Wiki

import React, { useState, useRef, useEffect } from "react";

const OtpLogin = ({ length = 4 }) => {
  const [otp, setOtp] = useState(new Array(length).fill(""));
  const inputref = useRef([]);

  useEffect(() => {
    if (inputref.current[0]) {
      inputref.current[0].focus();
    }
  }, []);
  const onChangeHandler = (event, index) => {
    const { value } = event.target;
    if (isNaN(value)) return;
    const newOtp = [...otp];
    newOtp[index] = value.substring(value.length - 1);
    setOtp(newOtp);
    if (value && index < otp.length - 1 && inputref.current[index + 1]) {
      const newIndex = newOtp.indexOf("");
      inputref.current[newIndex].focus();
    }
  };
  const keyPressHandler = (event, index) => {
    if (event.key === "Backspace" && !otp[index] && index > 0) {
      inputref.current[index - 1].focus();
    }
  };
  return (
    <div className="otp-container">
      {otp.map((val, index) => (
        <input
          key={index}
          value={val}
          ref={(input) => (inputref.current[index] = input)}
          onChange={(event) => onChangeHandler(event, index)}
          onKeyDown={(event) => keyPressHandler(event, index)}
        />
      ))}
    </div>
  );
};

export default OtpLogin;

Output

Screenshot 2024-01-15 at 5 53 03 PM
⚠️ **GitHub.com Fallback** ⚠️