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

339
Visualizações
How can I get onKeyDown event to work in Next.js/React

I'm building a website using Next.js, and currently I'm trying to get a simple function to run when pressing a key. The problem I'm having is that the onKeyDown event isn't being triggered like I expected. My code is as follows: <main onKeyDown={e => console.log("Key pressed")}>

Currently it's placed in the "main" element, which is the top root element of this component. I've tried placing the onKeyDown event in many of the other elements as well, without luck. I'm not sure if it's the placement which causes issues or my lack of understanding of how to use this event. Any help would be appreciated.

As for now I simply want it to write something in the console so that I can see that it triggers. I've tried using onKeyPress instead, as well as assigning a function to the event instead of a lambda expression, which shouldn't make a difference.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your component, use useEffect to add(and remove) the event listener to the document.

const Component = () => {

  useEffect(() => {
    const keyDownHandler = (e) => console.log(`You pressed ${e.code}.`);
    document.addEventListener("keydown", keyDownHandler);

    // clean up
    return () => {
      document.removeEventListener("keydown", keyDownHandler);
    };
  }, []);

  return <main>Press a key</main>;
};

You may even make a custom hook (beware of the dependency list):

const useKeyDown = (handler, deps = []) => {
  useEffect(() => {
    document.addEventListener("keydown", handler);
    // clean up
    return () => {
      document.removeEventListener("keydown", handler);
    };
  }, deps);
};

const Component = () => {
  useKeyDown((e) => console.log(`You pressed ${e.code}.`), []);
  return <main>Press a key</main>;
};
about 4 years ago · Juan Pablo Isaza Relatório
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