Modal Content
This is a simple modal component.
I create a custom Modal component in react typescript.
// src/components/ui/Modal.tsx import React, { useState, useEffect, useRef } from 'react'; interface ModalProps { isOpen: boolean; onClose: () => void; children: React.ReactNode; dismissable?: boolean; closeOnEsc?: boolean; closeButtonLabel?: string; size?: 'small' | 'medium' | 'large'; position?: 'center' | 'top' | 'bottom'; } const Modal: React.FC= ({ isOpen, onClose, children, dismissable = true, closeOnEsc = true, closeButtonLabel = '×', size = 'medium', position = 'center', }) => { const [isModalOpen, setIsModalOpen] = useState(isOpen); const modalRef = useRef (null); useEffect(() => { setIsModalOpen(isOpen); }, [isOpen]); useEffect(() => { const handleOutsideClick = (event: MouseEvent) => { if (dismissable && modalRef.current && !modalRef.current.contains(event.target as Node)) { onClose(); } }; const handleEscKey = (event: KeyboardEvent) => { if (closeOnEsc && event.key === 'Escape') { onClose(); } }; if (isModalOpen) { document.addEventListener('mousedown', handleOutsideClick); document.addEventListener('keydown', handleEscKey); } return () => { document.removeEventListener('mousedown', handleOutsideClick); document.removeEventListener('keydown', handleEscKey); }; }, [isModalOpen, onClose, dismissable, closeOnEsc]); if (!isModalOpen) { return null; } const getSizeStyle = () => { switch (size) { case 'small': return { width: '300px', maxWidth: '100%' }; case 'large': return { width: '800px', maxWidth: '100%' }; default: return { width: '500px', maxWidth: '100%' }; } }; const getPositionStyle = () => { switch (position) { case 'top': return { alignItems: 'flex-start' }; case 'bottom': return { alignItems: 'flex-end' }; default: return { alignItems: 'center' }; } }; return ( ); }; export default Modal;{children}
import Modal from "@/components/ui/Modal"; import { useState } from "react"; export default function Home() { const [visible, setVisible] = useState(false); return (); } setVisible(false)}> Modal Content
This is a simple modal component.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3