Skip to content

Instantly share code, notes, and snippets.

@phlickey
Created January 24, 2023 11:46
Show Gist options
  • Save phlickey/aea3b9b0780f074194d599deea55644c to your computer and use it in GitHub Desktop.
Save phlickey/aea3b9b0780f074194d599deea55644c to your computer and use it in GitHub Desktop.
const Modal: React.FC<{
renderContent: (props: { close: () => void }) => React.ReactNode;
renderHandle: (props: { open: () => void }) => React.ReactNode;
}> = ({ renderContent, renderHandle }) => {
const ref = useRef<HTMLDialogElement>(null);
const open = () => ref.current?.showModal();
const close = () => ref.current?.close();
return (
<>
<dialog className={styles.modal} ref={ref}>
{renderContent({ close })}
<button className={styles.close} onClick={close}>
x
</button>
</dialog>
{renderHandle({ open })}
</>
);
};
const MyApp = () => {
return (
<div>
<h1>welcome to my app</h1>
<Modal
renderContent={({ close }) => (
<div>
<h1>This is modal content</h1>
<button onClick={close}>Click here to close it </button>
</div>
)}
renderHandle={({open})=><button onClick={open}>Click here to open the modal</button>}
/>
<p>You can click the button above to open the modal.</p>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment