jaywcjlove / react-hotkeys

React component to listen to keydown and keyup keyboard events, defining and dispatching keyboard shortcuts.
https://jaywcjlove.github.io/react-hotkeys/
414 stars 22 forks source link

Binding to multiple instances fires the last instance #2

Open matthew-dean opened 6 years ago

matthew-dean commented 6 years ago

I have a component wrapped like this:

<Hotkeys
  keyName='enter'
  onKeyDown={this._onClick}
>
  <div
    className={`${styles.Interactive} ${props.outline ? styles.outline : ''} ${props.className}`}
    onClick={this._onClick}
    disabled={props.disabled}
    tabIndex={!props.disabled && '0'}
    role={!props.disabled && 'button'}
  >
    {props.children}
  </div>
</Hotkeys>

I've found that when I make multiple instances of this component and press the keyboard, the last instance will be the one fired. So, if I have 4 buttons, the last one, with its this.props will be the one passed into the this._onClick handler no matter which of the four was focused when the keyboard was triggered.

jaywcjlove commented 6 years ago
_onClick(e){
+  e.preventDefault();
}
render() {
  return(
    <Hotkeys
      keyName='enter'
      onKeyDown={this._onClick}
    >
      <div
        className={`${styles.Interactive} ${props.outline ? styles.outline : ''} ${props.className}`}
        onClick={this._onClick}
        disabled={props.disabled}
        tabIndex={!props.disabled && '0'}
        role={!props.disabled && 'button'}
      >
        {props.children}
      </div>
    </Hotkeys>
  )
}

@matthew-dean This is an event bubbling?

jaywcjlove commented 6 years ago

@matthew-dean You can not use the same _onClick event name.

prasid444 commented 3 years ago

Any update in this issue? I am facing same problem, while using multiple instances. Only last component is working.

shokmaster commented 3 years ago

The problem is that the event is attached to the , rather than the component tag:

https://github.com/jaywcjlove/react-hotkeys/blob/e7197a8d07b38de5293e4a74cf12e935035b6a4f/src/index.tsx#L49