Last active
May 3, 2023 13:21
-
-
Save macchiitaka/01867ec9b2e5534eb657dc313834b849 to your computer and use it in GitHub Desktop.
React Dialog component
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 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