OTPInput.js
1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, { useEffect, useRef, useState } from "react";
const OTPInput = ({ length = 4, onOtpSubmit = () => {}, otp, setOtp }) => {
const handleChange = (index, e) => {
const value = e.target.value;
if (isNaN(value)) return;
const newOtp = [...otp];
newOtp[index] = value.substring(value.length - 1);
setOtp(newOtp);
const combinedOtp = newOtp.join("");
if (combinedOtp.length === length) onOtpSubmit(combinedOtp);
if (value && index < length - 1 && inputRefs.current[index + 1]) {
inputRefs.current[index + 1].focus();
}
};
const handleClick = index => {
inputRefs.current[index].setSelectionRange(1, 1);
};
const handleKeyDown = (index, e) => {
if (e.key == "Backspace" && !otp[index] && index > 0 && inputRefs.current[index - 1]) {
inputRefs.current[index - 1].focus();
}
};
const inputRefs = useRef([]);
useEffect(() => {
if (inputRefs.current[0]) {
inputRefs.current[0].focus();
}
}, []);
// console.log("inputRefs", inputRefs);
return (
<div>
{otp.map((value, index) => {
return (
<input
key={index}
ref={input => (inputRefs.current[index] = input)}
type="text"
value={value}
onChange={e => {
handleChange(index, e);
}}
onClick={() => {
handleClick(index);
}}
onKeyDown={e => handleKeyDown(index, e)}
className="otpInput"
/>
);
})}
</div>
);
};
export default OTPInput;