Estoy tratando de hacer un clon de Wordle, ¿cómo me concentro en el siguiente campo de entrada después de que se haya disparado onChange (después de que el usuario haya ingresado una palabra)
import {useRef} from 'react'; const Mainarea = () => { // will use useState later in this const boxes = [{color: "white" , id:1 , userInput : ""} ,{color: "white" , id:2 , userInput : ""} ,{color: "white" , id:3 , userInput : ""} ,{color: "white" , id:4 , userInput : ""} ,{color: "white" , id:5 , userInput : ""}]; var value = "" const inputRef = useRef(""); return ( <div className="Mainarea"> <div className="mainBoxArea"> // This is the map function in question {boxes.map(box => { value = value + box.userInput; return( <div className="div" key = {box.id}> <input ref = {inputRef} className = "boxview" maxLength={1} type="text"/> </div> )})} </div> </div> ); } export default Mainarea; ----------Después de que el usuario haya agregado una palabra, quiero enfocarme automáticamente en el siguiente campo, ya que esta función de mapa se activará 5 veces
Primero, tiene una matriz de inputs , por lo que necesita una matriz de refs , y en la función handleChange puede ir a la siguiente input incrementando el índice en uno y usando el evento de focus en la input de destino en ese índice.
import { useRef, useEffect } from "react"; const Mainarea = () => { // will use useState later in this const boxes = [ { color: "white", id: 1, userInput: "" }, { color: "white", id: 2, userInput: "" }, { color: "white", id: 3, userInput: "" }, { color: "white", id: 4, userInput: "" }, { color: "white", id: 5, userInput: "" } ]; var value = ""; const inputRefs = useRef([]); useEffect(() => { inputRefs.current = inputRefs.current.slice(0, boxes.length); }, []); const handleChange = (i) => { if (i === boxes.length - 1) { return; } inputRefs.current[i + 1].focus(); }; return ( <div className="Mainarea"> <div className="mainBoxArea"> {boxes.map((box, i) => { value = value + box.userInput; return ( <div className="div" key={box.id}> <input ref={(el) => (inputRefs.current[i] = el)} className="boxview" maxLength={1} type="text" onChange={() => handleChange(i)} /> </div> ); })} </div> </div> ); }; export default Mainarea;