简体   繁体   中英

How can I place close button outside of modal window in react-modal?

I've imported Modal from react-modal (React Player is just for emdebbing video) and my code looks this way now:

<Modal
    isOpen={modalIsOpen}
    onRequestClose={closeModal}
    style={customStyles}
    contentLabel='Example Modal'
  >
    <button onClick={closeModal} className={css.button}>close</button>
    <ReactPlayer
      url='https://vimeo.com/49384334'
      playing='true'
      controls='true'
      volume={0}
    />
  </Modal>

So I tried to write some styles for button like that, but the button can't leave it's parent tag.

.button {
   display: block;
   float: right;
   position: relative;
   top: -10px;
   right: -10px;
   z-index: 1002;
 }

Are there any styles I should overwrite maybe in the modal div?

Make sure you set your styles correctly. A basic implementation like this should work

const modalStyles = {
  position: "relative"
};
const buttonStyles = {
  position: "absolute",
  top: "10px",
  right: "10px"
};
<Modal
  isOpen={this.state.isOpen}
  onRequestClose={this.handleOpenModal}
  style={modalStyles}
  contentLabel="Example Modal"
>
  <button onClick={this.handleOpenModal} style={buttonStyles}>
    close
  </button>
  modal content
</Modal>

By default Modal component from react-modal has overflow: auto . That is why your button can't move outside the modal. To fix this you need change overflow: auto to overflow: visible (see code below)

const modalStyles = {
    content : {
      top                   : '50%',
      left                  : '50%',
      right                 : 'auto',
      bottom                : 'auto',
      marginRight           : '-50%',
      transform             : 'translate(-50%, -50%)',
      overflow              : 'visibile'
    }
  };
const buttonStyles = {
  position: "absolute",
  top: "10px",
  right: "10px"
};

<Modal
  isOpen={this.state.isOpen}
  onRequestClose={this.handleOpenModal}
  style={modalStyles}
  contentLabel="Example Modal"
>
  <button onClick={this.handleOpenModal} style={buttonStyles}>
    close
  </button>
  modal content
</Modal>

Thank you.

If you can add the library classnames to your project then you can:

  1. Put the button outside of the modal:
<Modal>
    <ReactPlayer />
</Modal>
<button onClick={closeModal} >close</button>
  1. Add a conditional to your button:
<button onClick={closeModal} className={classNames(styles.button, {[styles.show]: modalIsOpen} )} >close</button>

Your styles should be something like:

.button = {
  display: none;
  position: fixed;
  ...
}
.show = {
  display: block;
  ...
}

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