While working on OTP verification in Reactjs, I encountered an error message when running my code:
Error: Cannot read properties of undefined (reading 'value')
import { useState, useEffect, useRef } from 'react'
import '../src/component.css'
export default function Component(){
const[count,setCount] = useState(0);
const inpRef = useRef([]);
useEffect(()=>{
setTimeout(()=>{
setCount(count+1)
},1000);
const handleInput =(e,index)=>{
const current = inpRef.current[index];
let next = inpRef.current[index+1];
let prev = inpRef.current[index-1];
const expression = /^\d+$/
const isValid = expression.test(e.target.value);
if(!isValid){
e.target.value = "";
return;
}
if (e.target.value.length >1){
e.target.value ="";
}
}
inpRef.current.forEach((input,index)=>{
input.addEventListener('input',handleInput.bind(null,index))
})
return ()=>{
inpRef.current.forEach((input,index)=>{
input.removeEventListener('input',handleInput.bind(null,index))
})
}
},[])
return(
<>
<p> Counter : {count}</p>
<h4>Now enter the OTP</h4>
<div className="whole">
<h5>Send the OTP to your phone Number</h5>
<div className="container">
{[...Array(6)].map((_,index)=>{
return <input className="text-field" type ="number"
ref = {(ref) =>{
inpRef.current[index] = ref;
}}
key ={index}
/>
})}
</div>
<button className ="btn">SUBMIT</button>
</div>
</>
)
}
Can you help me troubleshoot why I am getting this error? I am trying to create an OTP verification page with 6 input boxes where the focus automatically shifts to the next input when a value is entered, and shifts back when the backspace key is pressed.