Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
Disable default action on keyUp

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

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda