After the modal is open, focus is given to the modal content element, which is an element that is created by react-modal. When any key press is made on this element, it is not propagated to the child, so there is no way for anyone to define keypress events on the modal.
Keypress should be propagated down to the children - especially in the case that there is only one child, which is the parent of the rest of the content. Alternatively, Modal component should accept onKeyPress handler which is called if whatever keypress handler is on .ReactModal__Content element is not triggered (esc seems to be the only key that it's watching for). The latter seems easier to implement and more useful.
Eg left/right in image carousel.
+1
Possibly related to the issue I just reported: https://github.com/reactjs/react-modal/issues/198
@vshesh
I was faced with the same issue and implemented my own solution:
https://github.com/fritz-c/react-image-lightbox/blob/3f602ca51447938622c2b1f033c23e1343f83c17/src/react-image-lightbox.js#L955-L979
Boiled down, the fix is as follows:
<Modal
...
onAfterOpen={() => this.myEl && this.myEl.focus()} // Focus on the div with key handlers
>
<div
ref={el => { this.myEl = el; }}
tabIndex="-1" // Enables key handlers on div
onKeyDown={this.handleKeyInput}
>
...
I have also found a workaround using this component: https://github.com/jossmac/react-images
However, since I needed a custom component rendered rather than just an array of images, I extended it by allowing a single child component to be rendered: https://github.com/vshesh/react-images
Would be great if react-modal supported this, regardless. Given a modal is supposed to be generic and a lightbox is supposed to be specific, I'd rather make a lightbox out of a modal than a modal out of a lightbox.
@vshesh @fritz-c react-modal should forward this event, example:
<Modal onKeyDown={mycallback} ...></Modal>
mycallback(event) should actually be fired and if esc is pressed, it must request to close the modal and also pass forward the event.
@fritz-c solution is the best way to handle this.
I'm closing this issue for clean up. Thank you!
It's been a few years... but I'm having the same issue and @fritz-c's solution doesn't seem to work for me. Focus remains trapped on the Modal element (ReactModal__Content). I'm trying to listen for left/right arrow keydown events to control a slideshow that lives in the modal.
Hey guys i am still facing this issue,, spent so much time on this.. until i found its bug here... please fix this.. its 2021 (5 YEARS). 馃槃
@m-nathani PR are always welcome. 馃槃
Most helpful comment
@vshesh
I was faced with the same issue and implemented my own solution:
https://github.com/fritz-c/react-image-lightbox/blob/3f602ca51447938622c2b1f033c23e1343f83c17/src/react-image-lightbox.js#L955-L979
Boiled down, the fix is as follows: