Bladeren bron

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 jaren geleden
bovenliggende
commit
4892975af0
1 gewijzigde bestanden met toevoegingen van 23 en 0 verwijderingen
  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)
     setTimeout(this.positionModal, 100)
   }
   }
 
 
+  componentWillReceiveProps(newProps) {
+    if (this.props.isOpen === true && newProps.isOpen === false) {
+      this.handleModalClose()
+    }
+  }
+
   componentWillUpdate() {
   componentWillUpdate() {
     setTimeout(this.positionModal, 100)
     setTimeout(this.positionModal, 100)
   }
   }
@@ -68,6 +74,22 @@ class NewModal extends React.Component {
     setTimeout(this.positionModal, 100)
     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() {
   positionModal() {
     let pageNode = this.modalDiv && this.modalDiv.node.firstChild
     let pageNode = this.modalDiv && this.modalDiv.node.firstChild
     let contentNode = pageNode && pageNode.firstChild
     let contentNode = pageNode && pageNode.firstChild
@@ -145,6 +167,7 @@ class NewModal extends React.Component {
         contentLabel={this.props.contentLabel || this.props.title}
         contentLabel={this.props.contentLabel || this.props.title}
         style={modalStyle}
         style={modalStyle}
         onRequestClose={this.props.onRequestClose}
         onRequestClose={this.props.onRequestClose}
+        onAfterOpen={() => { this.handleModalOpen() }}
       >
       >
         {this.renderTitle()}
         {this.renderTitle()}
         {children}
         {children}