Created
August 25, 2022 07:48
-
-
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
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 { 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