Answer the question
In order to leave comments, you need to log in
What is the correct way to deal with keyboard events in a React SPA page?
I need to implement the functionality of canceling an action on the page when the user presses the Ctrl + Z combination.
How to work with this? I didn't find anything in the documentation about this.
Everywhere methods of work are described only through passing a parameter to a specific component, but I need to work with the page.
In my functional component, to receive the event, I did this:
document.onkeypress = keyPress;
const keyPress = e => console.log(e);
Answer the question
In order to leave comments, you need to log in
useEffect(() => {
const onKeypress = e => console.log(e);
document.addEventListener('keypress', onKeypress);
return () => {
document.removeEventListener('keypress', onKeypress);
};
}, []);
You can put a handler on the document in the component itself, but if the event handler is used only in this component, then you need to subscribe to the event when mounting the component, and unsubscribe when unmounting
https://reactjs.org/docs/state-and-lifecycle.html
If the component is a class, then you can use the componentDidMount and componentWillUnmount life
cycle
methods .
completion
https://developer.mozilla.org/en-US/docs/Web/API/E...
https://developer.mozilla.org/en-US/docs/Web/API/E...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question