react-modalを使用してモーダルを表示する
react-modalサンプル
リンク
GitHub
GitHub - reactjs/react-modal: Accessible modal dialog component for React
ドキュメント
react-modal documentation
npm install
npm install react-modal
サンプルコード
import React, { useState } from 'react'; import Modal from 'react-modal'; const customStyles = { content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)', }, }; const AppTestView = () => { const [modalIsOpen, setIsOpen] = useState(false); let subtitle; const openModal = () => { setIsOpen(true); }; const afterOpenModal = () => { subtitle.style.color = '#f00'; }; const closeModal = () => { setIsOpen(false); }; return ( <div> <button type="button" onClick={openModal}>Open Modal</button> <Modal isOpen={modalIsOpen} onAfterOpen={afterOpenModal} onRequestClose={closeModal} style={customStyles} contentLabel="Example" ariaHideApp={false} > <h2 ref={(_subtitle) => { subtitle = _subtitle; return subtitle; }} > Hello </h2> <button type="button" onClick={closeModal}>close</button> <div>i am a modal</div> <form> <input /> <button type="button">sample</button> </form> </Modal> </div> ); }; export default AppTestView;
コードは殆ど公式サンプル通りです。
ボタンのonClick
イベントでreact hooks
を利用して、modalIsOpen
をtrue
にします。
modalIsOpen
がtrue
になると、<Modal>
タグ内のJSXがモーダルとして表示されます。
公式サンプルとの差異は以下の通り
ariaHideApp
プロパティを設定
上記コンポーネントではサンプルと異なり、コンポーネントをappElement
にバインドしていません。
そのため、アプリ要素が定義されていないとエラーが発生します。
そのため、非推奨ですが、ariaHideApp
プロパティを設定しています。
subtitle
変数の設定
<h2>
タグのref
プロパティをair-bnb eslint
のエラーが発生しない形に変更。
こちらはreact-modalと特に関係しないので、気にしないでも大丈夫です。