When user type value on <input />
, I want to switch focus.
But my issue is when I type value on refOne
, codeOne is empty on checkFocus
function, event I try to use setTimeout
.
Strange thing is console.log('render codeOne', codeOne)
has value, but codeOne inside the function is empty.
How to fix it ?
import React, { useState, ChangeEvent, useRef, useEffect } from 'react';
function ModalPhoneBox() => {
const refOne = useRef<HTMLInputElement>(null);
const refTwo = useRef<HTMLInputElement>(null);
const refThree = useRef<HTMLInputElement>(null);
const [codeData, setCodeData] = useState<FormInputType>({
codeOne: '',
codeTwo: '',
codeThree: '',
});
const { codeOne, codeTwo, codeThre } = codeData;
const checkFocus = () => {
console.log('checkFocus');
setTimeout(() => {
if (
refOne.current != null &&
refTwo.current != null &&
refThree.current != null &&
refFour.current != null
) {
console.log('0');
console.log('codeOne', codeOne);
if (codeOne && codeTwo === '') {
console.log('1');
refTwo.current.focus();
}
if (codeOne && codeTwo && codeThree === '') {
console.log('2');
refThree.current.focus();
}
}
}, 1000);
};
console.log('render codeOne', codeOne);
return (
<div className={styles.inputGroup}>
<div className={styles.inputBox}>
<input
ref={refOne}
maxLength={1}
onChange={(v: ChangeEvent<{ value: string }>) => {
setCodeData({ ...codeData, codeOne: v.target.value });
checkFocus();
}}
type="text"
placeholder={''}
/>
</div>
<div className={styles.inputBox}>
<input
ref={refTwo}
maxLength={1}
onChange={(v: ChangeEvent<{ value: string }>) => {
setCodeData({ ...codeData, codeTwo: v.target.value });
checkFocus();
}}
type="text"
placeholder={''}
/>
</div>
<div className={styles.inputBox}>
<input
ref={refThree}
maxLength={1}
onChange={(v: ChangeEvent<{ value: string }>) =>
setCodeData({ ...codeData, codeThree: v.target.value })
}
type="text"
placeholder={''}
/>
</div>
</div>
);
export default ModalPhoneBox;