I have to perform the following steps on an array:
- Create an array of refs outside the component
- create a form
- 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
My code is the following:
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;
The last point doesn't work, how can I change the code to make it work? Solved
The only problem is that I can't write in the inputs. Solved
If I wanted to use an Input component that takes the ref via forwardRef.