feat: add Modal component

This commit is contained in:
ValdiANS
2025-10-02 11:45:11 +07:00
parent 14046a1add
commit ca9205618a
+62
View File
@@ -0,0 +1,62 @@
'use client';
import { ReactNode, RefObject, useCallback, useRef, useState } from 'react';
import { cn } from '@/lib/helper';
export const useModal = () => {
const ref = useRef<HTMLDialogElement>(null);
const [open, setOpen] = useState(false);
const openModal = useCallback(() => {
setOpen(true);
ref.current?.showModal();
}, []);
const closeModal = useCallback(() => {
setOpen(false);
ref.current?.close();
}, []);
const toggle = useCallback(() => {
if (open) {
closeModal();
} else {
openModal();
}
}, [open]);
if (ref.current) {
ref.current.addEventListener('close', () => {
closeModal();
});
}
return { ref, open, setOpen, openModal, closeModal, toggle } as const;
};
interface ModalProps {
ref: RefObject<HTMLDialogElement | null>;
children?: ReactNode;
closeOnBackdrop?: boolean;
className?: {
modal?: string;
modalBox?: string;
};
}
const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
return (
<dialog ref={ref} className={cn('modal', className?.modal)}>
<div className={cn('modal-box', className?.modalBox)}>{children}</div>
{closeOnBackdrop && (
<form method='dialog' className='modal-backdrop'>
<button>close</button>
</form>
)}
</dialog>
);
};
export default Modal;