mousetrap
mousetrap copied to clipboard
Mousetrap takes precedence over React's keyboard events?
Consider this snippet:
class TestComponent extends React.Component {
handleInputKeyDown(e) {
e.stopPropagation();
console.log("input key down", e.key);
}
handleWrapperKeyDown(e) {
e.stopPropagation();
console.log("wrapper key down", e.key);
}
componentDidMount() {
Mousetrap(this.wrapper).bind('esc', this.handleWrapperKeyDown, 'keydown');
}
componentWillUnmount() {
Mousetrap(this.wrapper).unbind('esc');
}
render() {
return (
<div ref={(elem) => this.wrapper = elem}>
<input onKeyDown={this.handleInputKeyDown} />
</div>
)
}
}
Since the <input />
exists inside the <div />
, I would expect that handleInputKeyDown
is called before handleWrapperKeyDown
when focused on the input element. But instead, handleWrapperKeyDown
is called. Is this a know issue/feature? This can make incrementally converting a large codebase to Mousetrap difficult.
Here's a demonstration of the issue: https://jsfiddle.net/k7uuofaL/15/
Would be curious if anyone else has come up with a work around for this. We've tried some pretty hacky things and nothing has been able to consistently prevent the mousetrap handler from being called...
React 17 should fix this: https://reactjs.org/blog/2020/10/20/react-v17.html#changes-to-event-delegation but unfortunately we are blocked from upgrading for now.
ran into this today as well
preventDefault is an okay workaround but it might disable other things