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);
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With