0

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.

T S
  • 245
  • 2
  • 10

1 Answers1

2

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);
}, [])
T S
  • 245
  • 2
  • 10