简体   繁体   中英

How to make a modal responsive in reactjs

I have a simple modal in react. I'm trying to make it responsive. When it's a desktop, its height and width is fixed. When it's a desktop and the modal is open, the background should not be scrollable. Only the modal should be scrollable. When it's a mobile, the modal takes full full width and height.

I've managed to get the modal to work but having issues making the modal full width and height when its a mobile. I'm also having issues making the background not scrollable.

I've created an example on code-sandbox https://codesandbox.io/s/simple-react-bulma-modal-u2tyd

You are using bulma to style your html which do not provide styles you required for mobile devices out of the box, so you need to add them manually. There are several options how to do that. One of them: you need to create css class and "wrap" it into media query @media so that you can detect device width and apply appropriate styles:

// Add this to your styles.css file

@media (max-width: 680px) {
  .modal-card-customization {
    height: 100vh;
    max-height: 100vh;
  }
}

// And apply this class for the modal in index.js file

// .... your previous code here

  <div className="modal-background" />
  <div className="modal-card modal-card-customization">

// .... rest of your code here 

In order to disable scrollbar once the modal is open you can apply overflow: hidden style on document.body , like so:

    // index.js file

//.... your previous code here

    const active = this.state.isModal ? "is-active" : "";
    
    if (active) {
      document.body.style = 'height: 100vh; overflow: hidden';
    } else {
      document.body.style = ''
    }
    
//.... rest of your code here 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM