LoginSignup
16
21

More than 3 years have passed since last update.

React-modalで簡易モーダル作成

Last updated at Posted at 2019-06-19

React-modalでお手軽モーダル作成

いざ作るとなると案外めんどくさいモーダルウインドウ
ReactだとReact-modalで簡単に実装できるが、ちょっと悩んだので書き残し

$ npm install react-modal

で導入

Modal.setAppElementを設定してないとエラーが発生するので忘れないように!

ModalWindow.js
import React from 'react';
import Modal from 'react-modal';
const customStyles = {
  content : {
    top                   : '50%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)'
 }
};

Modal.setAppElement('#your-app') //任意のアプリを設定する create-react-appなら#root
class ModalWindow extends React.Component {
  constructor() {
    super();
    this.state = {
      modalIsOpen: false
    };
    this.openModal = this.openModal.bind(this);
    this.afterOpenModal = this.afterOpenModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
  }
  openModal() {
    this.setState({modalIsOpen: true});
  }
  afterOpenModal() {
    this.subtitle.style.color = '#f00';
  }
  closeModal() {
    this.setState({modalIsOpen: false});
  }
  render() {
    return (
      <div>
        <button onClick={this.openModal}>Open Modal!!</button>
        <Modal
          isOpen={this.state.modalIsOpen}
          onAfterOpen={this.afterOpenModal}
          onRequestClose={this.closeModal}
          style={customStyles}
          contentLabel="Example Modal"
        >
          <h2 ref={subtitle => this.subtitle = subtitle}>ModalWindow</h2>
          <div>Opend</div>
            <button onClick={this.closeModal}>close</button>
        </Modal>
      </div>
    );
  }
}
export default ModalWindow;

モーダルウインドウとモダールを開くトリガーになるボタンを実装している

<Modal></Modal>

の中身がモーダルになる

あとはこれをボタンを配置したいとこに置けばOK

16
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
21