Skip to content

Instantly share code, notes, and snippets.

@macchiitaka
Last active May 3, 2023 13:21
Show Gist options
  • Save macchiitaka/01867ec9b2e5534eb657dc313834b849 to your computer and use it in GitHub Desktop.
Save macchiitaka/01867ec9b2e5534eb657dc313834b849 to your computer and use it in GitHub Desktop.
React Dialog component
import type { DialogHTMLAttributes } from "react";
import { forwardRef, useCallback, useEffect, useState } from "react";
declare global {
interface HTMLDialogElement {
show(): void;
showModal(): void;
close(): void;
}
}
export const Dialog = forwardRef<
HTMLDialogElement,
DialogHTMLAttributes<HTMLDialogElement> & { isModal?: boolean }
>(({ isModal = true, open, ...restProps }, ref) => {
const [el, setEl] = useState<HTMLDialogElement | null>(null);
const combinedRef = useCallback(
(e: HTMLDialogElement | null) => {
if (typeof ref === "function") {
ref(e);
} else if (ref) {
ref.current = e;
}
setEl(e);
},
[ref]
);
useEffect(() => {
if (open && isModal) {
el?.showModal();
return () => el?.close();
}
if (open && !isModal) {
el?.show();
return () => el?.close();
}
el?.close();
return () => {};
}, [el, isModal, open]);
return <dialog ref={combinedRef} {...restProps} />;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment