Przeglądaj źródła

Disable background scroll if modal is open

If the modal is opened on top of scrollable content, allow scrolling
only for the opened modal, disabling the scrollable content's scroll.
When closing the modal, restore scrolling functionality and scrolling
position to modal's parent's scrollable content.
Sergiu Miclea 8 lat temu
rodzic
commit
4892975af0
1 zmienionych plików z 23 dodań i 0 usunięć
  1. 23 0
      src/components/molecules/Modal/Modal.jsx

+ 23 - 0
src/components/molecules/Modal/Modal.jsx

@@ -56,6 +56,12 @@ class NewModal extends React.Component {
     setTimeout(this.positionModal, 100)
   }
 
+  componentWillReceiveProps(newProps) {
+    if (this.props.isOpen === true && newProps.isOpen === false) {
+      this.handleModalClose()
+    }
+  }
+
   componentWillUpdate() {
     setTimeout(this.positionModal, 100)
   }
@@ -68,6 +74,22 @@ class NewModal extends React.Component {
     setTimeout(this.positionModal, 100)
   }
 
+  handleModalOpen() {
+    this.windowScrollY = window.scrollY
+    document.body.style.top = `${-this.windowScrollY}px`
+    document.body.style.position = 'fixed'
+    document.body.style.width = '100%'
+    document.body.style.height = '100%'
+  }
+
+  handleModalClose() {
+    document.body.style.top = ''
+    document.body.style.position = ''
+    document.body.style.width = ''
+    document.body.style.height = ''
+    window.scroll(0, this.windowScrollY)
+  }
+
   positionModal() {
     let pageNode = this.modalDiv && this.modalDiv.node.firstChild
     let contentNode = pageNode && pageNode.firstChild
@@ -145,6 +167,7 @@ class NewModal extends React.Component {
         contentLabel={this.props.contentLabel || this.props.title}
         style={modalStyle}
         onRequestClose={this.props.onRequestClose}
+        onAfterOpen={() => { this.handleModalOpen() }}
       >
         {this.renderTitle()}
         {children}