📖

Reactでモダール作成:react-modal

に公開

reactでモーダルを実装したい時のメジャーなライブラリreact-modalの使い方

react-modal で簡単に実装してみる

①インストール

npm install react-modal
or
yarn add react-modal

②セットアップ

import Modal from 'react-modal';

Modal.setAppElement('#root');

③基本的な使い方

import React, { useState } from 'react';
import Modal from 'react-modal';

Modal.setAppElement('#root');

const ModalExample = () => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>モーダルを開く</button>
      
      <Modal
        isOpen={isOpen}
        onRequestClose={() => setIsOpen(false)}
        contentLabel="Example Modal"
      >
        <h2>モーダルの中身</h2>
        <button onClick={() => setIsOpen(false)}>閉じる</button>
      </Modal>
    </>
  );
};

export default ModalExample;

表示イメージ

④スタイルカスタマイズ方法

<Modal
  isOpen={isOpen}
  onRequestClose={() => setIsOpen(false)}
  style={{
    content: {
      top: '50%',
      left: '50%',
      right: 'auto',
      bottom: 'auto',
      transform: 'translate(-50%, -50%)',
      padding: '2rem',
    },
    overlay: {
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
  }}
>

⑤モーダルが表示されないとき

下記CSSを追加(モーダルが透明or非表示になっている)

.modal {
  background: white;
  padding: 20px;
  max-width: 400px;
  margin: auto;
  border-radius: 8px;
  position: relative;
}

.overlay {
  background-color: rgba(0, 0, 0, 0.6);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

公式ドキュメント

https://reactcommunity.org/react-modal/

91works Tech Blog

Discussion