I'm creating a game like wordle and, to do this, when the user writes a letter, the app should focus the next input. I can't do this, and I don't know why.
const GameLine = (props) => {
const lineIndex = props.index;
const checkTry = () => {
const userGuess = firstLetter ' ' secondLetter ' ' thirdLetter ' ' fourthLetter ' ' fifthLetter;
console.log(userGuess);
}
const [firstLetter, setFirstLetter] = useState(null);
const [secondLetter, setSecondLetter] = useState(null);
const [thirdLetter, setThirdLetter] = useState(null);
const [fourthLetter, setFourthLetter] = useState(null);
const [fifthLetter, setFifthLetter] = useState(null);
const handleNextInput = (e) => {
console.log("ID atual: " e.target.id);
const fieldName = e.target.id.split('-')[1];
const nextSibiling = document.getElementById(`box${lineIndex}-${parseInt(fieldName) 1}`);
console.log(nextSibiling);
if(nextSibiling !== null){
nextSibiling.focus();
}
}
return (
<BoxesDiv>
<Box1 type="text" id={ `box${lineIndex}-1`} onChange={(e) => { handleNextInput(e); setFirstLetter(e.target.value)}} value={firstLetter} />
<Box2 type="text" id={ `box${lineIndex}-2`} onChange={(e) => setSecondLetter(e.target.value)} value={secondLetter} onKeyPress={(e)=>handleNextInput(e)}/>
<Box3 type="text" id={ `box${lineIndex}-3`} onChange={(e) => { handleNextInput(e); setThirdLetter(e.target.value)}} value={thirdLetter} />
<Box4 type="text" id={ `box${lineIndex}-4`} onChange={(e) => { handleNextInput(e); setFourthLetter(e.target.value)}} value={fourthLetter} />
<Box5 type="text" id={ `box${lineIndex}-5`} onChange={(e) => setFifthLetter(e.target.value)} value={fifthLetter} onKeyPress={ (e)=>{ if(e.key === "Enter"){checkTry()} } }/>
</BoxesDiv>
);
}
I'm trying to get the next input with id and use Element.focus(), but nothing happens. Could someone help me to find where's my error?
Thanks
CodePudding user response:
You should called handleNextInput function for second box. I think you could onKeyUp function for handleNextInput.
<Box2 onKeyUp={(e)=>handleNextInput(e)} ... />
CodePudding user response: