Skip to content

Commit

Permalink
Merge 7f2482d into 98dd5be
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Holloway committed Dec 8, 2019
2 parents 98dd5be + 7f2482d commit 418ae8b
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/components/ModalPortal.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ export default class ModalPortal extends Component {

this.shouldClose = null;
this.moveFromContentToOverlay = null;

// Body focus trap see Issue #742
this.bodyFocusTrapBefore = document.createElement("div");
this.bodyFocusTrapBefore.style.position = "absolute";
this.bodyFocusTrapBefore.style.opacity = "0";
this.bodyFocusTrapBefore.setAttribute("tabindex", "0");
this.bodyFocusTrapAfter = this.bodyFocusTrapBefore.cloneNode();
this.bodyFocusTrapBefore.addEventListener("focus", this.focusContent);
this.bodyFocusTrapAfter.addEventListener("focus", this.focusContent);
}

componentDidMount() {
Expand Down Expand Up @@ -151,6 +160,16 @@ export default class ModalPortal extends Component {
ariaHiddenInstances += 1;
ariaAppHider.hide(appElement);
}

if (document.body.firstChild !== this.bodyFocusTrapBefore) {
document.body.insertBefore(
this.bodyFocusTrapBefore,
document.body.firstChild
);
}
if (document.body.lastChild !== this.bodyFocusTrapAfter) {
document.body.appendChild(this.bodyFocusTrapAfter);
}
}

afterClose = () => {
Expand Down Expand Up @@ -191,6 +210,13 @@ export default class ModalPortal extends Component {
if (this.props.onAfterClose) {
this.props.onAfterClose();
}

if (this.bodyFocusTrapBefore.parentElement === document.body) {
document.body.removeChild(this.bodyFocusTrapBefore);
}
if (this.bodyFocusTrapAfter.parentElement === document.body) {
document.body.removeChild(this.bodyFocusTrapAfter);
}
};

open = () => {
Expand Down

0 comments on commit 418ae8b

Please sign in to comment.