Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created August 25, 2022 07:48
Show Gist options
  • Save guillermodlpa/987fc504ee8db7475c106933c5ebfa2c to your computer and use it in GitHub Desktop.
Save guillermodlpa/987fc504ee8db7475c106933c5ebfa2c to your computer and use it in GitHub Desktop.
Pattern to add a confirmation dialog to confirm a button action, with TypeScript. Dialog not implemented here, as it depends on the UI library
import { EventHandler, useCallback, useState } from 'react';
import ConfirmationDialog from './ConfirmationDialog';
export default function WrappingDialogConfirmation({
children,
...props
}: {
children: (handleClick: EventHandler<any>) => React.ReactNode;
title: string;
description: string;
onConfirm: () => Promise<unknown> | void;
}) {
const [dialogOpen, setDialogOpen] = useState(false);
const handleClick = useCallback((event: React.UIEvent) => {
event.stopPropagation();
setDialogOpen(true);
}, []);
return (
<>
<ConfirmationDialog
{...props}
isOpen={dialogOpen}
onCancel={() => {
setDialogOpen(false);
}}
onRequestClose={() => {
setDialogOpen(false);
}}
/>
{children(handleClick)}
</>
);
}
// Usage example. With Chakra UI
<WrappingConfirmationDialog
onConfirm={handleRemove}
title='Are you sure?'
description="If you do this, there's no way back"
danger
confirmButtonLabel='Remove'
>
{handleClick => (
<Button variant='ghost' colorScheme='error' onClick={handleClick}>
Remove
</Button>
)}
</WrappingConfirmationDialog>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment