mousetrap icon indicating copy to clipboard operation
mousetrap copied to clipboard

Mousetrap takes precedence over React's keyboard events?

Open ben-z opened this issue 6 years ago • 3 comments

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/

ben-z avatar Jan 26 '18 23:01 ben-z

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.

maclockard avatar Apr 08 '21 01:04 maclockard

ran into this today as well

tarngerine avatar Apr 29 '21 14:04 tarngerine

preventDefault is an okay workaround but it might disable other things

tarngerine avatar Apr 29 '21 15:04 tarngerine