Tengo que realizar los siguientes pasos en una matriz:
Mi código es el siguiente:
const array = new Array(5).fill(createRef()); const Step1 = () => { return ( <> {/*Form */} <form style={{margin:30}} > {/*- inside the form make a map of the array and render an input for each element, - the input (when in focus) at the press of "enter" puts the next input in focus if there is any, otherwise it submits the form */} {array.map((item, index) => { return ( <input key={index} ref={item} type="text" placeholder={`Input ${index + 1}`} onKeyPress={(e) => { if (e.key === "Enter") { if (array[index + 1]) { array[index + 1].current.focus(); } else { e.preventDefault(); console.log("submit"); } } }} /> ); })} <button type="submit">Submit</button> </form> </> ) } export default Step1;El último punto no funciona, ¿cómo puedo cambiar el código para que funcione? Resuelto
El único problema es que no puedo escribir en las entradas. Resuelto
Si quisiera usar un componente de entrada que toma la referencia a través de forwardRef.
Tienes dos problemas. El problema principal es su uso de Array#fill() que, cuando se usa así, llena la matriz con referencias a un solo objeto. Como tal, está terminando con una sola ref a la que asigna sucesivamente cada entrada. La solución es mapear la matriz y devolver una nueva ref en cada iteración.
const array = new Array(5).fill(null).map(() => createRef()); // or const array = Array.from({length: 5}, () => createRef()); Su segundo problema es que enter envía automáticamente el formulario, por lo que debe preventDefault() en el nivel superior del bloque if .
const { createRef } = React; const array = Array.from({length: 5}, () => createRef()); const Step1 = () => { function focusNextRef(e, index) { if (e.key === 'Enter') { e.preventDefault(); // <-- move preventDefault() if (array[index + 1]) { array[index + 1].current.focus(); } else { console.log('submit'); } } } return ( <div> <form style={{ margin: 30 }} > {array.map((item, index) => { return ( <input key={index} ref={item} type="text" placeholder={'Input ' + (index + 1)} onKeyPress={(e) => focusNextRef(e, index)} /> ); })} <button type="submit">Submit</button> </form> </div> ); }; ReactDOM.render( <Step1 />, document.getElementById('root') ); <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="root"></div>