【TypeScript】Reactでモーダルを実装してみるよ!


1. モーダルコンポーネントの作成

import React from 'react';
import './Modal.css';

type ModalProps = {
  show: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
};

const Modal: React.FC<ModalProps> = ({ show, onClose, title, children }) => {
  if (!show) {
    return null;
  }

  return (
    <div className="modal-overlay">
      <div className="modal">
        <div className="modal-header">
          <h2>{title}</h2>
          <button onClick={onClose} className="modal-close-button">
            ×
          </button>
        </div>
        <div className="modal-content">
          {children}
        </div>
      </div>
    </div>
  );
};

export default Modal;

2. モーダルの基本的なスタイリングを追加

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  max-width: 500px;
  width: 100%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.modal-close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
}

.modal-content {
  font-size: 1rem;
}

3. モーダルを使用します

import React, { useState } from 'react';
import Modal from './Modal';
import './App.css';

const App: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const openModal = () => setIsModalOpen(true);
  const closeModal = () => setIsModalOpen(false);

  return (
    <div className="App">
      <header className="App-header">
        <h1>React Modal Example</h1>
        <button onClick={openModal} className="open-modal-button">Open Modal</button>
      </header>

      <Modal show={isModalOpen} onClose={closeModal} title="Example Modal">
        <p>This is the content of the modal</p>
        <button onClick={closeModal} className="close-modal-button">Close</button>
      </Modal>
    </div>
  );
};

export default App;


4. Appのスタイリング

.App {
  text-align: center;
  padding: 50px;
}

.App-header {
  margin-bottom: 40px;
}

.open-modal-button,
.close-modal-button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

.open-modal-button:hover,
.close-modal-button:hover {
  background-color: #0056b3;
}

ぜひ、ご参考ください!

是非フォローしてください

最新の情報をお伝えします