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を利用して、modalIsOpentrueにします。
modalIsOpentrueになると、<Modal>タグ内のJSXがモーダルとして表示されます。

公式サンプルとの差異は以下の通り

  • ariaHideAppプロパティを設定
    上記コンポーネントではサンプルと異なり、コンポーネントappElementにバインドしていません。
    そのため、アプリ要素が定義されていないとエラーが発生します。
    そのため、非推奨ですが、ariaHideAppプロパティを設定しています。

発生するエラーの情報
javascript - "Warning: react-modal: App element is not defined. Please use `Modal.setAppElement(el)` or set `appElement={el}`" - Stack Overflow

  • subtitle変数の設定
    <h2>タグのrefプロパティをair-bnb eslintのエラーが発生しない形に変更。
    こちらはreact-modalと特に関係しないので、気にしないでも大丈夫です。