In my form, I want to use keyboard arrow keys to move between the input fields.
Here is the Codesandbox example. (Click inside the last input field and use the UP arrow key to move up to the previous sibling input field.
Code:
const arrowDownPosition = React.useRef();
const getCurElePosition = (eTarget) => {
const mum = eTarget.parentElement.parentElement;
const parent = mum.parentElement;
const children = Array.from(parent.children);
let taskNum;
children.forEach((el, i) => {
const elChild = el.children[0].children[0];
if (elChild === eTarget) {
taskNum = i;
}
});
return [taskNum, parent, children, mum];
};
const keyUpHandler = (e) => {
e.preventDefault();
if (e.key === "ArrowUp") {
e.target.setSelectionRange(
arrowDownPosition.current[0],
arrowDownPosition.current[1]
);
}
};
const keyHandler = (e) => {
e.stopPropagation();
const eTarget = e.target;
const [elePosition, parent, children, mum] = getCurElePosition(eTarget);
if (e.key === "ArrowUp") {
let previousSiblingRef;
children.forEach((ele, i) => {
if (ele == mum && i - 1 >= 0) {
previousSiblingRef = i - 1;
}
});
if (previousSiblingRef) {
const { selectionStart, selectionEnd } = eTarget;
arrowDownPosition.current = [selectionStart, selectionEnd];
const previousSibling =
children[previousSiblingRef].children[0].children[0];
previousSibling.focus();
previousSibling.setSelectionRange(selectionStart, selectionEnd);
}
}
};
The above solution is a hacky way of solving the problem. You can see the caret move to the start of the previous input field before its moved to my intended position. I am using useRef to store the value.
This is because I am unable to stop the keyUp default handler before my code is run?
Thank you