react-modal Dynamic Sizing

user172902 picture user172902 · Oct 21, 2018 · Viewed 22.8k times · Source

Im using react-modal which is pretty great. Is it possible to dynamically size it (perhaps with css media tag). For example,

  1. For large screen, the modal only takes up a small potion of the screen (lets say max width 200px;
  2. For medium screen, the modal takes up most of the screen (Lets say 80% of the screen width and height
  3. For mobile device, it takes takes up 100% of the width and height.

Answer

ene_salinas picture ene_salinas · Oct 25, 2018

Have a look at this code that prepare for you.

ReactModal.setAppElement('#main');

class ExampleApp extends React.Component {
  constructor () {
    super();
    this.state = {
      showModal: false
    };

    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
  }

  handleOpenModal () {
    this.setState({ showModal: true });
  }

  handleCloseModal () {
    this.setState({ showModal: false });
  }

  render () {
    return (
      <div>
        <button onClick={this.handleOpenModal}>Trigger Modal</button>
        <ReactModal 
           isOpen={this.state.showModal}
           contentLabel="onRequestClose Example"
           onRequestClose={this.handleCloseModal}
           className="Modal"
           overlayClassName="Overlay"
        >
          <p>Modal text!</p>
          <button onClick={this.handleCloseModal}>Close Modal</button>
        </ReactModal>
      </div>
    );
  }
}

const props = {};

ReactDOM.render(<ExampleApp {...props} />, document.getElementById('main'))

Checkout in responsive view:

https://codepen.io/ene_salinas/full/yRGMpG/

Checkout full code:

https://codepen.io/ene_salinas/pen/yRGMpG

Yellow color = large screen
Green color = medium screen
Gray color = Mobile

Don't forget this meta:

"<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">"

Happy coding.