Reputation: 1404
I would like key events from the whole page be handled by my top-level react component. But the component doesn't take up all space. One solution would be to use window.addEventListener
in componentDidMount
. However if I do it that way I will use native javascript event handling globally, and react event handling for some specific components. I'm worried that this might lead to problems down the line.
What is the best way to add global event handling in a React app?
Upvotes: 0
Views: 1627
Reputation: 781
Setting a listener with addEventListener in componentDidMount sounds reasonable- that's a pretty standard approach for "window level" events like this. It's ok to still use component-level React event listeners for component-specific events. You'll just want to make sure to also use removeEventListener in componentWillUnmount to clean up the listener(s) you added.
Upvotes: 1