Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created February 24, 2025 13:51
Show Gist options
  • Save allenhwkim/73ce51b7cc7f6cfee8d709b7c60df1d6 to your computer and use it in GitHub Desktop.
Save allenhwkim/73ce51b7cc7f6cfee8d709b7c60df1d6 to your computer and use it in GitHub Desktop.
React Dialog
.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%;
}
}
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