How can we bind to window key events in a componen...
# compose-web
j
How can we bind to window key events in a component? I'm looking for something similar to Angular's
@HostListener('window:keydown.escape')
that registers on the window while a component is active
o
I think DisposableEffect can help with subscribing and unsubscribing at the right moment. But the event listener for the window key events has to be provided by yourself.
j
I could use window.add/removeEventListener, looks like window doesn't have
onKeyDown
afaics
d
What's the use case you're trying to solve?
In case any of us can suggest a different approach
j
Basically when on a certain page, I want to be able to press escape to go to an upper page
it's different than "back" because each page has a defined parent that it will navigate to
d
I did something where I put up an invisible overlay that handles escape, would that work in your case?
j
Well the whole page has to be interactable, I feel like since
window
supports key events I shouldn't need to modify the page at all, just escape from anywhere on the page should bring them to the upper level
I think DisposableEffect is a good approach, just it would be nice to be able to have a better onKeyDown for the
window
similar to as we can do on the elements
d
You can probably install your own key handling object at a top level then (maybe some root overlay that fills the whole screen) and have that be the thing that allows you to press esc to go back or not, maybe have it own its own stack of elements separate from the browser history stack