When the modal is closed it focuses on the last focused input field/button. This is unexpected and not clearly documented. I had a button that was only visible when focusing on a particular element using a CSS transform. Focusing on the input field caused it's container to scroll to the button which caused the CSS transform to hide the button on focus.
With example
Results: The CSS transformation is no longer in its original state. The focus is now placed on the button which caused the container to scroll to the button. Hovering over it hides the button and reveals whatever is below. In my case there was nothing below the buttons.
Modal will close without restoring focus on last focused input field / button.
https://codesandbox.io/s/74x8ynqr6q
When I hover over the menu the visible icon scrolls out of view and a button to open a modal scrolls into view. When clicking on the button it brings up the react-modal. When the react modal is closed the icon is no longer visible though the button to open the modal is visible. The CSS transformation now shows nothing when hovering over the menu.
ReactModal is placing focus on the hidden button causing the view of the menu to focus on the wrong thing in it's initial state.
This is related to https://github.com/reactjs/react-modal/issues/675
I found a work around to this. In the function that gets called onClick I blur off of the input field/button before opening the modal and it appears to have solved the issue.
<button onClick={ (e) => {
e.currentTarget.blur();
props.openModal()
}}> Open Modal </button>
would the shouldReturnFocusAfterClose prop fix your problem?
@mattlub yeah that would work great.
@trevlar Thanks for reporting this issue and the example. I'll try to find sometime to debug this.
@mattlub Thanks for the help.
react-modal relies on the last document.activeElement to know which element it should give back focus. Ideally, the expected behaviour should be "Open React Modal" button to be the last active element.
Firefox and Safari have the same behaviour - they don't set the button as the active element after click on it.
Chrome will actually focus the button when clicked.
IE and Edge - needs testing.
openModal = () => {
debugger;
document.activeElement; // to make it easy to inspect.
this.setState({ modalOpen: true });
};
After changing the openModal method, you can step through to see which element has been the last element on the document.activeElement.
Using the keyboard to navigate will produce the expected behaviour on all browsers.
Safari: Version 11.1.2 (13605.3.8)
Firefox: 61.0.2 (64-bit)
Chrome: Version 68.0.3440.106 (Official Build) (64-bit)
Most helpful comment
would the
shouldReturnFocusAfterCloseprop fix your problem?http://reactcommunity.org/react-modal/#usage