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

166
Views
Listen for keypress / keydown event locally in react router component

I want to listen to keydown event in a local react-router component and it will run a function if a certain key was pressed. But because the event listener is added to document object, if I'm on a different page it will still try to run the function, resulting in error since the function is local to my component.

For example if I am in login page (domain.com/login), the login page component loads in <main>, and <header> remains constant. And so I want to run a function which is in my login component, when the person presses Enter, it will press the login button / aka run the login function which is called when the button is pressed.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The return keyword will run when the component unmounts

useEffect(() => {
    function onKeyDown(e) {
        if (e.key === "Enter") {
            console.log("ENTER PRESSED")
            submit()
        }
    }
    
    document.addEventListener("keydown", onKeyDown) 

    return () => document.removeEventListener('keydown', onKeyDown);
}, [])
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!