P
P
Pavel Didenko2019-05-23 10:08:20
React
Pavel Didenko, 2019-05-23 10:08:20

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);

Is this the right way to work in React?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-05-23
@Dasslier

useEffect(() => {
  const onKeypress = e => console.log(e);

  document.addEventListener('keypress', onKeypress);

  return () => {
    document.removeEventListener('keypress', onKeypress);
  };
}, []);

V
Vladimir, 2019-05-23
@Casufi

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 question

Ask a Question

731 491 924 answers to any question