Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!