Skip to content

Instantly share code, notes, and snippets.

@GeeWee
Created March 1, 2019 10:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeeWee/b8a0d57ea2a591c7900d21ba54854572 to your computer and use it in GitHub Desktop.
Save GeeWee/b8a0d57ea2a591c7900d21ba54854572 to your computer and use it in GitHub Desktop.
interface ConfirmDialogConfig {
title: string;
text: string;
deleteButtonText: string;
}
/**
* A hook that will allow you to prompt a user for confirmation before doing a delete, by showing a "Are you sure" modal.
* @param action - the action to be performed when the user presses delete
* @param config - The strings that the modal should contain
* Returns an object containing two things.
* A "deleteConfirmDialog" which is a dialog that should be {rendered} somewhere in your JSX
* A "showDialog" function that should be called when you want to prompt the user if they're sure.
*/
export function useDeleteConfirmDialog(
action: () => void,
config: ConfirmDialogConfig,
): { showDialog: () => void; deleteConfirmDialog: React.ReactNode } {
const [isOpen, setOpen] = useState(false);
return {
showDialog: () => setOpen(true),
deleteConfirmDialog: (
<Dialog
open={isOpen}
onClose={() => setOpen(false)}
aria-labelledby="delete-dialog-title"
aria-describedby="delete-dialog-description"
>
<DialogTitle id="delete-dialog-title">{config.title}</DialogTitle>
<DialogContent>
<DialogContentText id="delete-dialog-description">{config.text}</DialogContentText>
</DialogContent>
<DialogActions>
<DeleteButton
onClick={() => {
action();
setOpen(false);
}}
autoFocus
>
{config.deleteButtonText}
</DeleteButton>
<Button onClick={() => setOpen(false)} variant="contained" color="primary">
Fortryd
</Button>
</DialogActions>
</Dialog>
),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment