Created
February 24, 2025 13:51
-
-
Save allenhwkim/73ce51b7cc7f6cfee8d709b7c60df1d6 to your computer and use it in GitHub Desktop.
React Dialog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.dialog-modal { | |
border: 0; | |
border-radius: 0.5rem; | |
width: 50%; | |
height: 75%; | |
padding: 0; | |
overflow: auto; | |
background-color: #f6f6f6; | |
&::backdrop { | |
background: hsl(0 0% 0% / 50%); | |
} | |
.btn-close { | |
position: sticky; | |
float: right; | |
color: var(--bs-secondary); | |
top: 4px; | |
right: 8px; | |
z-index: 1; | |
font-size: .75rem; | |
cursor: pointer; | |
} | |
> :not(.btn-close) { | |
height: 100%; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useEffect } from 'react'; | |
import './DialogModal.scss'; | |
interface ModalProps { | |
isOpen: boolean; | |
hasCloseBtn?: boolean; | |
onClose?: () => void; | |
children: React.ReactNode; | |
}; | |
export default function DialogModal({isOpen, hasCloseBtn, onClose, children}: ModalProps) { | |
const modalRef = useRef<HTMLDialogElement>(null); | |
useEffect(() => { | |
const modalEl = modalRef.current; | |
if (!modalEl) return; | |
isOpen ? modalEl.showModal() : modalEl.close(); | |
}, [isOpen]); | |
function closeModal() { | |
onClose?.(); | |
modalRef.current?.close(); | |
}; | |
return ( | |
<dialog className="dialog-modal shadow-sm" ref={modalRef} | |
onClick={ e => e.target === modalRef.current && closeModal()} | |
onKeyDown={e => (e.key === 'Escape') && closeModal()}> | |
{hasCloseBtn && | |
<div | |
className="btn-close" | |
aria-label="Close" | |
onClick={closeModal}> | |
</div> | |
} | |
{children} | |
</dialog> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment