Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - onKeyDown event

I'm creating my own lightbox in React, and I have problem with implementation keyDown event. When I open image I want to have key a for image - 1 and d key for image + 1. I only implemented console.log(e.key) to check if all works properly. And I found an issue, that my KeyDown event only works when I have focus on button left or right. When I click on photo keys don't work.

Lightbox:

<div 
  onKeyDown={this.nextButtonImage} 
  onClick={this.closeLightbox} 
  className="lightbox-container">
  <div className="lightbox">
    <button onClick={this.closeLightbox} className="lg-close">
      <i className="fas fa-times" />
    </button>
    <button onClick={this.prevImage} className="lg-arrows lg-left">
      <i className="fas fa-caret-left" />
    </button>
    <button onClick={this.nextImage} className="lg-arrows lg-right">
      <i className="fas fa-caret-right" />
    </button>
    <img src={this.images[this.state.openImage].url} alt="" />
  </div>
</div>

keyDown event:

nextButtonImage = (e) => {
  console.log(e.key);
}
like image 426
Freestyle09 Avatar asked Oct 16 '22 11:10

Freestyle09


1 Answers

This is correct because event keydown is attached to an element. The default context come back useful when you are working with inputs. When you need a global event (as events are propagated top/down) you can rely on window object or document object:

componentDidMount(){
  document.addEventListener('keydown', (event) => {
    const keyName = event.key;
    alert('keydown event\n\n' + 'key: ' + keyName);
  });
}

componentWillUnmount(){ 
  // Remove the listener before unmount
}
like image 138
Mosè Raguzzini Avatar answered Nov 15 '22 08:11

Mosè Raguzzini