Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Created September 14, 2023 18:04
Show Gist options
  • Save mike-pete/0763d619ea5890333aab04244be7f258 to your computer and use it in GitHub Desktop.
Save mike-pete/0763d619ea5890333aab04244be7f258 to your computer and use it in GitHub Desktop.
React Modal using Dialog
import { memo, useEffect, useRef } from "react"
const Dialog: React.FC<{ open: boolean, className?:string, children:React.ReactElement }> = ({ open, className, children }) => {
const dialogRef = useRef<HTMLDialogElement>(null)
useEffect(() => {
if (open) {
if(dialogRef.current?.open){
dialogRef.current?.close()
}
dialogRef.current?.showModal()
} else {
dialogRef.current?.close()
}
}, [open])
return (
<dialog className={className} ref={dialogRef}>
{children}
</dialog>
)
}
export default memo(Dialog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment