I want to implement the TAB behavior, but with pressing ENTER.
Here is my attempt to solve it, but it doesn't work due to not using Refs
.
My idea is to state in each input, which element should be focused next, and the Enter keyup event handler setting that value as the new focused field.
I've seen examples using useHook
but I can't figure how to use it, without spamming a ton of useState
's for each input.
Here is a Sandbox of the code below.
import React, { useState, useEffect } from "react";
function Form(props) {
// Holds the ID of the focused element
const [focusedElementId, setFocusedElementId] = useState("input-one");
// The actual focusing, after each re-render
useEffect(() => {
document.getElementById(focusedElementId).focus();
}, []);
useEffect(() => {
console.log("STATE:", focusedElementId);
}, [focusedElementId]);
// When Enter is pressed, set the focused state to the next element ID provided in each input
function handleKeyUp(e) {
e.which = e.which || e.keyCode;
if (e.which == 13) {
let nextElementId = e.target.attributes["data-focus"].value;
console.log(`HANDLER: Enter - focusing ${nextElementId}`);
setFocusedElementId(nextElementId);
}
}
return (
<div>
<div className="form-items" style={{ display: "flex" }}>
<div className="input-group">
<label>{"Input One"}</label>
<br />
<input
type={"text"}
id={"input-one"}
onKeyUp={handleKeyUp}
data-focus={"input-two"}
/>
</div>
<div className="input-group">
<label>{"Input Two"}</label>
<br />
<input
type={"text"}
id={"input-two"}
onKeyUp={handleKeyUp}
data-focus={"input-three"}
/>
</div>
<div className="input-group">
<label>{"Input Three"}</label>
<br />
<input
type={"text"}
id={"input-three"}
onKeyUp={handleKeyUp}
data-focus={"input-one"}
/>
</div>
</div>
</div>
);
}
export default Form;